There’s already rudimentary collision detection in the app, but only for the sides. What if I wanted the balls to detect when they collide?
In the demo video you can already see the balls colliding (and, incidentally, the gravity changing from down, then left, up, right, and down again). But how did I get there? Wouldn’t you know that XNA has a built-in structure called BoundingSphere that can handle that for you? I defined the bounding sphere as centered around the ball’s center point (which was defined by the texture’s dimensions), and used the z-coordinate as 0. Intrinsically, then, the bounding sphere acts like a bounding circle as long as everything is on the same Z-plane.
Next, I created a couple interfaces that are going to help me out. Interfaces such as IPhysical and IPhysicalSphere — they provide necessary information for collidable objects. Here they are:
By implementing these properties, a separate class can be constructed to perform the necessary math for bouncing balls. When first implemented, colliding balls would simply switch speed vectors. However, that only works if balls collide straight on (so that movement vectors would be inverse of each other). When balls collide like this:
(Awesome MS-Paint artwork, huh?)
When balls collide like that, they don’t simply exchange vectors. What actually happens is that the speed vectors are changed according to the normal line between the two circles (or the normal plane between the two spheres).
I created a static class to do this work for me:
This was inspired by a blog post I found that covered it exceptionally. I wish I could name the offer but I couldn’t find the author’s name!
Calling this method to adjust the speed vectors is done whenever collisions are detected. That part is handled in the Game class during the Update method:
And that’s about all there is to it! New source code is up! Here’s the next demo:
One other thing — as a note, the red ball with the orange gradient has a mass of 8.0f; the others have a mass of 4.0f.