9 Collision detection
This chapter covers
- Object Collision Detection
- Applying collision detection between our enemies and the player’s bullet
In most games, especially action games, there will be the need to know when one or more objects collide with each other. With our sample game being a shoot-em up we need to know when our enemy objects encounter both our player and any player’s bullets.
At this stage, our enemies are all a fixed size, but later we will introduce more enemies of different sizes, so we will need to take this into account with the collision detection routine we will introduce in this chapter.
9.1 Object Collision Detection
Our first step is to write a function that works out whether two objects of different sizes have hit each other.
Now how do we check whether two objects have hit each other? It requires a little bit of math. In the interest of simplicity and saving calculation time, instead of working out whether the actual pixels of two objects are touching, we treat all objects as rectangles.
What we are trying to do is work out whether two rectangles intersect as follows:
Figure 9.1 Detecting the collision of two objects.
![](https://drek4537l1klr.cloudfront.net/cruise/v-3/Figures/ch-09__image001.png)
Let’s break down the problem into some smaller steps, first by picking one direction. It doesn’t matter whether we look at each object’s X or Y positions (if we stick with one direction at a time).