O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Detecting When a Sprite Hits Another Sprite

There’s no point throwing flaming fireballs at an alien if it’s not even going to raise an eyebrow. To make this game fun, we need to make the alien sprite react when it’s hit. Most games involve sprites hitting each other (bats and balls, targets and weapons, chasing and catching), so collision detection, as it is often called, is a staple of game design.

warning_bomb.eps You can detect whether the fireball is touching the alien sprite from the fireball, but it is the alien that must react, so that’s where we need to put our script.

You can use a Sensing block to check whether a sprite is touching another sprite, and we combine that with an If block to trigger a reaction when the alien and fireball touch each other.

Like the key press detection for the ship, we want to keep checking for the alien being hit throughout the game, so we put the If block inside a Forever block (see Figure 11-10). Inside the first If block are the instructions for what to do when the alien is touching the fireball: Change the alien’s costume to what it looks like when it’s been hit, make it say “Arggh!” in a speech bubble, play a sound effect, and then hide the alien. After a random delay of a few seconds, the alien is repositioned at the top of the screen, switched back to its normal costume and shown, so the horrible cycle of invasion and destruction can begin again.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required