2D Collision Detection

Collision detection is used for a number of purposes in a game. It is when two objects “collide” or meet, and we need to find out where this occurs. Once detected, we can then take some action.

Some specific examples of this are below. Usually this is game specific.

Player collision with the screen

Sometimes in a game, we wish the player to be visible, but if we are not careful, the player could be made invisible or partially visible.

One example of this is below in a space invaders type game where the player moves their ship left and right only.

To fix this, we need to calculate that if the player reaches the end of the screen, then it will display the player fully at the edge of the screen, but not go off screen. To do this, monitor the x co-ordinate and calculate (screen width – width of ship) if moving right and calculate (screen width + width of ship) if moving left. You could do a similar thing if you allow the ship to move up and down, but in this case, you need to monitor the y co-ordinate.

Two objects colliding with each other

Sometimes we need to detect when two objects collide or come in contact with each other.

For a 2D game, one way to do this is to see if two rectangles overlap each other. One way to calculate this mathematically and by using code is shown here.

One example of this is below in a space invaders type game. In the case below, we need to work out mathematically when a ship’s bullet hits an alien. Then if the alien is hit, the alien is moved off the screen (or not shown anymore) and the player scores some points.

Another example is below of an alien bullet hitting the player’s ship. Once the bullet hits the ship, the ship then explodes.