Post by johnno56 on Jun 14, 2019 21:09:20 GMT -6
This is a smallbasic demo (author unknown) that I converted to RC.
I have not experimented with a 'practical' maximum number of objects but it might be fun to test the theory...
I have not experimented with a 'practical' maximum number of objects but it might be fun to test the theory...
xmax = 600
ymax = 600
WindowOpen(0,"2D Collision - ESC to quit",0,0,xmax,ymax,0)
Window(0)
CanvasOpen(0,xmax,ymax,0,0,xmax,ymax,0)
Canvas(0)
clearcanvas
m = 8
n = m ^ 2
dim x[n]
dim y[n]
dim vx[n]
dim vy[n]
dim mass[n]
dim collisionflag[n,n]
ed = 1
u = 0
' Initial variables
for a = 0 to m - 1
for b = 0 to m - 1
x[u] = 50 * a + 10
y[u] = 50 * b + 10
vx[u] = rand(4) '(rnd * 100 / 100) - 0.5
vy[u] = rand(4) '(rnd * 100 / 100) - 0.5
mass[u] = 5 + rand(11) '7
u = u + 1
next
next
sub collision()
'dim collisionflag[6,6]
' collision detection
for u1 = 0 to n-2
for u2 = u1+1 to n-1
dx = x[u2]-x[u1]
dy = y[u2]-y[u1]
distance = (dx * dx + dy * dy) ^ 0.5
if distance < (mass[u1] + mass[u2]) then
if collisionflag[u1,u2] = 0 then
' vx and vy calc
ax = dx / distance
ay = dy / distance
va1 = vx[u1] * ax + vy[u1] * ay
vb1 = 0 - vx[u1] * ay + vy[u1] * ax
va2 = vx[u2] * ax + vy[u2] * ay
vb2 = 0 - vx[u2] * ay + vy[u2] * ax
vaP1 = va1 + (1 + ed) * (va2 - va1) / (1 + mass[u1] / mass[u2])
vaP2 = va2 + (1 + ed) * (va1 - va2) / (1 + mass[u2] / mass[u1])
vx[u1] = vaP1 * ax - vb1 * ay
vy[u1] = vaP1 * ay + vb1 * ax
vx[u2] = vaP2 * ax - vb2 * ay
vy[u2] = vaP2 * ay + vb2 * ax
collisionflag[u1,u2] = 1
end if
else
collisionflag[u1,u2] = 0
end if
next
next
end sub
' main loop
While 1=1
clearcanvas
for u = 0 to n-1
If x[u] < mass[u] or x[u] > (600 - mass[u]) then
vx[u] = 0 - vx[u]
end if
If y[u] < mass[u] or y[u] > (600 - mass[u]) then
vy[u] = 0 - vy[u]
end if
x[u] = x[u] + vx[u]
y[u] = y[u] + vy[u]
setColor(rgb(u * 7,0,255 - u * 7))
circleFill(x[u],y[u],mass[u])
next
update()
collision()
if key(k_escape) = 1 then
end
end if
wend