Collision detection is essential in a game, unless we are playing cards or chess. What good is a driving game if it cannot recognize whether we hit a tree or collided with another car. Physical contact between game objects plays critical role in the game and the feeling the user gets from it.
In this article we will only scratch the surface of the problem. I just want to show how to integrate collision detection in game. Algorithms for fast and accurate collision detection can be from very simple to really complex and hard to understand, depending on the type of objects and virtual world the reside in.
No matter how complex the shapes of the objects are the basic principles remain the same. Things collide when they try to occupy the same point at the same time. For the needs of this article we will modify the sample found in the keyboard interaction sample. Instead of a triangular ship moving around we will build a simple squash game.
To keep things simple we will concentrate in 2D collisions between rectangular objects. This will make the collision test function fast and so we will be able to concentrate in what happens behind the scenes.
In order to be accurate we have to check every object in our game against all the other objects and see if they collide. Here comes the first simplification that will speed the tests up without sacrificing accuracy. We do not have to test the walls against each other. We put them there and even if they intersect we are sure it's OK. So we just have to check the moving objects against the static environment as well as against each other. This reduces the number of test we need to do by a lot.
When should we test for collisions?
Well we test for collision after we apply the movement on our objects. This means that in the 'frame_move' function calls the collision detection function before it returns. This function then checks whether the ball has hit the walls or the bat. If the ball hits any of the vertical (side) walls it changes its horizontal speed. it hits the top wall or the bat it changes the vertical speed. This is a simple bounce effect.
The collision test function between two objects is very simple. Since the objects are rectangular and they only span in the X and Y direction we just have to check if the horizontal distance of their centers is smaller than the half of the sum of their widths. Similarly in the Y direction we check their vertical distance against the half of the sum of their heights. It is not a very sophisticated algorithm for collision detection but it is enough for starters. However complex and advance it might be we would still apply in it the same way.