Learning LibraryGame Development LibraryKids

Collision detection: telling when things touch

Games need to know when two things touch. A laser and an enemy. A player and a coin. That check is called collision detection. It's what makes a hit count.

The big idea

Collision detection checks whether two sprites overlap, so your game can react when they do.

See it in code

1Start simple

A touch is just a yes-or-no. Here two things sit at the same spot, so touching is True — and the if reacts:

python
laser_x = 240
enemy_x = 240

touching = laser_x == enemy_x
if touching:
    print("Hit!")
Run it — same spot, so it counts as a hit:
Hit!

touching is True or False. The if only fires when it's True. Real collisions work the same way — a yes-or-no, then a reaction.

2A step further

Now real sprites. A Laser and an Enemy sit on the same spot, and laser.hits(enemy) checks the overlap for us — no math to write:

python
from game import Stage, Enemy, Laser

screen = Stage.create()
Stage.clear(screen)

enemy = Enemy(240, 200)
laser = Laser(240, 200)

if laser.hits(enemy):
    print("The laser hit the enemy!")

enemy.draw(screen)
laser.draw(screen)
Run it — the laser is right on the enemy, so it's a hit:
The laser hit the enemy!
A purple enemy sprite mid-screen with a thin yellow laser overlapping it.

hits() did the checking and gave back True, so the message printed. Miss the enemy and it would be False instead.

3In our world

Now make the hit count. Same overlap, but this time a True from hits() adds to the score and shows it on the HUD:

python
from game import Stage, Enemy, Laser, HUD

screen = Stage.create()
Stage.clear(screen)

hud = HUD()
enemy = Enemy(240, 200)
laser = Laser(240, 200)

if laser.hits(enemy):
    hud.add_score(50)
    print("Hit! Score is now", hud.score)

enemy.draw(screen)
hud.draw(screen)
Run it — the laser overlaps the enemy, so it counts as a hit:
Hit! Score is now 50
A purple enemy sprite mid-screen with a heads-up display reading SCORE 50 and LIVES 3.

The laser and enemy overlapped, so hits() was True. That made the if run: score up by 50. If the laser had missed, hits() would be False, and nothing would happen.

The same idea, everywhere

Collision is everywhere in games. A player grabs a coin. A ball bounces off a wall. A car crosses a finish line. Spot the touch, then decide what happens: score, bounce, win, or lose.

Try it yourself

Move the laser to Laser(240, 50) so it misses the enemy — now the message won't print. Then check a second enemy against the same laser with another if.

The common mistake

Checking for a hit but forgetting to do something about it. laser.hits(enemy) only gives you True or False — you still need an if to add the score or remove the enemy. The check and the reaction go together.

What it unlocks

Collision uses conditionals on sprites, and feeds score and lives.