04-16-2024, 03:59 PM
I wrote a quick test for how collisions between moving objects (player and enemies) and the static walls should work in that 3d thing I'm working on. In the game/engine I will just check for collisions with walls close to the moving objects (a uniform grid will contain information about which walls passes through each cell). But maybe someone may still find this test useful for their own purposes:
This is pretty much how I did it in the GLOOM library for n6 too, if my memory is correct (source code since long gone).
Code:
set window "Collision", 640, 480
set redraw off
lines = []
randomize 11
for i = 1 to 8
ln = [rnd(640), rnd(480), rnd(640), rnd(480)]
dx = ln[2] - ln[0]; dy = ln[3] - ln[1]
ln[6] = sqr(dx*dx + dy*dy)
ln[4] = dx/ln[6]
ln[5] = dy/ln[6]
lines[sizeof(lines)] = ln
next
obj = Object(320, 240, 16)
while not keydown(KEY_ESCAPE, true)
'obj.x = mousex(); obj.y = mousey()
if keydown(KEY_LEFT) obj.x = obj.x - 4
if keydown(KEY_RIGHT) obj.x = obj.x + 4
if keydown(KEY_UP) obj.y = obj.y - 4
if keydown(KEY_DOWN) obj.y = obj.y + 4
PushOut(obj, lines)
set color 0, 0, 0
cls
set color 255, 255, 255
DrawLines(lines)
obj.Draw()
set caret width(primary)/2, 0
center "Use the arrow keys to move the circle around"
redraw
fwait 60
wend
function DrawLines(lines)
foreach ln in lines draw line ln[0], ln[1], ln[2], ln[3]
endfunc
function Object(x, y, r)
return [x: x, y: y, r: r, rsqr: r*r,
Draw: function(); draw ellipse .x, .y, .r, .r, false; endfunc]
endfunc
function PushOut(obj, lines)
' Let all lines push the object around a maximum of 10 times. This is not a recommended
' approach, just for testing.
tests = 10
for i = 1 to tests
col = false
foreach ln in lines
dp = max(0, min(ln[6], (obj.x - ln[0])*ln[4] + (obj.y - ln[1])*ln[5]))
px = ln[0] + dp*ln[4]; py = ln[1] + dp*ln[5]
dx = obj.x - px; dy = obj.y - py
d = dx*dx + dy*dy
if d < obj.rsqr
k = 1/sqr(d)
obj.x = px + dx*k*obj.r
obj.y = py + dy*k*obj.r
col = true
endif
next
if not col break
next
endfunc
This is pretty much how I did it in the GLOOM library for n6 too, if my memory is correct (source code since long gone).