Posted: 23rd Feb 2004 1:12
Let me know if anyone finds any bugs in it.

+ Code Snippet
REM 2D ball physics using vectors
REM Coded by: Phaelax (Phaelax@hotmail.com)
REM Website: http://www.dbspot.com/krytek/

randomize timer()

velocity# = 2

type ball
   x as float
   y as float
   r as float
   vx as float
   vy as float
   angle as float
endtype

amount = 10

dim c(amount) as ball

for i=1 to amount
   c(i).r = 20
   c(i).x = rnd(screen width()-40)+20
   c(i).y = rnd(screen height()-40)+20
   c(i).angle = rnd(360)
   c(i).vx = sin(c(i).angle) * velocity#
   c(i).vy = cos(c(i).angle) * velocity#
next i


do
   cls


   for a = 1 to amount
      for b = 1 to amount
         if a <> b
            if (c(a).x-c(b).x)^2 + (c(a).y-c(b).y)^2 <= (c(a).r+c(b).r)^2

               tx# = c(b).x - c(a).x
               ty# = c(b).y - c(a).y
               angle# = wrapvalue(atanfull(tx#, ty#)+180)
               c(a).vx = sin(angle#)*velocity#
               c(a).vy = cos(angle#)*velocity#
               c(a).angle = angle#

               tx# = c(a).x - c(b).x
               ty# = c(a).y - c(b).y
               angle# = wrapvalue(atanfull(tx#, ty#)+180)
               c(b).vx = sin(angle#)*velocity#
               c(b).vy = cos(angle#)*velocity#
               c(b).angle = angle#
            endif
         endif
      next b
   next a


   for i=1 to amount
      gosub _check_sides
      c(i).x = c(i).x + sin(c(i).angle) * velocity#
      c(i).y = c(i).y + cos(c(i).angle) * velocity#

      circle c(i).x, c(i).y, c(i).r
   next i


   set cursor 0,0
   print "FPS: ", screen fps()

loop




_check_sides:
   if (c(i).x + c(i).r >= screen width()) OR (c(i).x <= c(i).r)
      c(i).vx = c(i).vx * -1
      c(i).angle = atanfull(c(i).vx, c(i).vy)
   endif

   if (c(i).y <= c(i).r) OR (c(i).y + c(i).r >= screen height())
      c(i).vy = c(i).vy * -1
      c(i).angle = atanfull(c(i).vx, c(i).vy)
   endif

RETURN
Posted: 23rd Feb 2004 1:41
No bugs here!

Even changing 'amount' to loads it still works. If I change velocity to a small number like 0.1 so I can see what's going on I notice a small overlap when two circles touch at their 'corners' but not enough to worry about. May just be way that DB draws circles.

To test it is doing 'proper' ball collisions I changed radius from 20 to 50 and it really does work.