# Help with 2D Collision Detection

• ### Question

• I have been trying to create a program that models elastic collisions between balls in 2D. It seems to work fine for two balls and ok for three but as I increase the number of balls I seem to get quite a lot of collisions that go undetected and the balls just pass straight through each other.

I think the problem is in the loop used to check the array of balls and the distance between their centres but I'm not sure.

In case anyone was wondering whether the actual collision calculations were derived by me unfortunately not. After making many a hash of doing the velocity calculations I found a great forum post by litdev which explains it quite nicely (http://social.msdn.microsoft.com/Forums/en-US/smallbasic/thread/41543a0d-01cf-4161-b280-f01d6c0511c8)

The exported code is : XFP905

Thanks for any help,

Joe

Wednesday, May 15, 2013 7:30 PM

• The problem is often due to 'tunneling' when a ball from on step to the next passes right though another and is never actually overlapping.

Could remedy by smaller velocities or multiply by a a timestep size (<1) but would appear slower, could reduce delay.

However, I think the issue in this case may also be here:

For j = 2 To Ball_Number

Should be

For j = i+1 To Ball_Number

In this way each ball pair is checked once - also faster!

There is also an issue if the balls are initially overlapping.

Import XFP905-1

Great program by the way.

• Marked as answer by Thursday, May 16, 2013 12:13 PM
Wednesday, May 15, 2013 8:45 PM

### All replies

• The problem is often due to 'tunneling' when a ball from on step to the next passes right though another and is never actually overlapping.

Could remedy by smaller velocities or multiply by a a timestep size (<1) but would appear slower, could reduce delay.

However, I think the issue in this case may also be here:

For j = 2 To Ball_Number

Should be

For j = i+1 To Ball_Number

In this way each ball pair is checked once - also faster!

There is also an issue if the balls are initially overlapping.

Import XFP905-1

Great program by the way.

• Marked as answer by Thursday, May 16, 2013 12:13 PM
Wednesday, May 15, 2013 8:45 PM
• Thanks for your post and posting that thread by LitDev. I studied physics at high school many years ago and that was the end of that until I started programming. When we did motion I don't think we applied the trig to handle the vectors. New territory for me. Thx.

Here's a link to another LitDev thread on calculating and adding acceleration to a ball down a slope.