Collision detection decides whether game objects occupy overlapping space. In a shoot-em-up, it determines whether a player bullet hits an enemy and whether an enemy reaches the player. It can run as part of movement logic or as its own game-loop step. section 1.5.3 section 9.0
A fast approach treats every object as an axis-aligned rectangle rather than testing individual pixels. Store each rectangle’s X and Y position, width, and height; two objects collide only when their ranges overlap on both the X and Y axes. section 9.1
Test rectangles with early exits:
- Compare the first object’s right edge with the second object’s X position. If it is left of the second object, stop: there is no collision. section 9.1
- Compare the second object’s right edge with the first object’s X position. If it is left of the first object, stop. section 9.1
- Repeat both separation tests vertically, using Y positions and heights. Passing all four tests means the rectangles intersect. section 9.1
- Return immediately on a non-hit so the routine spends few processor cycles on objects that are separate. section 9.1
Figure 9.1 Detecting the collision of two objects
Use the rectangle diagram to see why overlap must be checked independently across both axes. section 9.1
A reusable routine reserves eight bytes for the two objects’ positions and dimensions. It checks X separation, then Y separation, returning a set carry flag for a collision and a clear carry flag when objects do not overlap. section 9.1
Bullet hits a meteor
Set the bullet rectangle once before the enemy loop, then set each on-screen enemy’s position and dimensions before calling the collision routine. On a hit, erase the bullet and enemy sprites and clear the enemy’s active-data flag. Keeping this work inside the existing movement loop avoids a second pass through enemies. section 9.2 section 9.3
The same overlap idea can handle enemy-player contact. After confirming the player is not already dead, detect an enemy at the player’s vertical level and horizontally overlapping the ship; then reduce lives, request a display update, mark the player dead, and remove the enemy. section 11.1 section 11.0
