Saturday, December 14, 2013

Ball Physics Part 2

In this post the plan is to create multiple balls, program collision detection and collision resolving between the balls.

First thing to do is to declare an array of the Ball structure. To set the number off balls I will use a constant - #define NumOfBalls

Next we initialize the array and set it's size using our constant value. 





Next we update the Game class constructor to set values too all members of the array using a loop.  I have also given each ball a different size and position.




Next we update all the functions regarding the ball, again looping through every member. The player controlled ball will be ball 0 of the array. 




Compiling and running:

Everything works fine. Now I will get on with the collision detection. The algorithm will be simple - I will create a function which will check if the distance between the centers of each ball is less than the sum of those ball's radii. That function will check just that. Whether the balls collide, it will return true or false respectively.

Next function will be about resolving collision. Since I have not learned my physics lesson about elastic collision, I will just go ahead and switch the two balls' velocities, just to check if my method of detection is working properly. I will use pointers for this function, because I still haven't thought of a more efficient way.


After that at the bottom of the UpdateBall function we create another loop, which checks the other balls if they are colliding with the ball that is currently indexed. This code is highly inefficient but for a small amount of balls onscreen it will do just fine.

Time to compile and see the end result:


As we see the collision system works properly. In the next posts I will try to make it more realistic, with a more complex approach to the collision resolving function. 
Source code

No comments:

Post a Comment