How to Add Collision to a Game in Scratch - dummies

How to Add Collision to a Game in Scratch

By Derek Breen

Collision is at the heart of most videogames. Whether it’s Pac-Man colliding with a pink ghost, Mario jumping onto a platform, or your character picking up a new tool in Minecraft, a game designer decides what will happen when each collision occurs.

What collisions does your Flappy Bat game need to detect? Does the bat touch the pipe? Does the bat touch the ground? If either collision happens, what should occur? The game must end.

Detect collision with the Ground sprite

  1. Click the Ground sprite and then click the Scripts tab.

  2. Drag the following blocks into the Scripts Area and select Player in the TOUCHING block.

    image0.jpg

  3. Click the Green Flag button.

    If the player floats to the ground, the game should end as soon as they collide.

    image1.jpg

You will usually put an IF THEN block inside a FOREVER block so the program will keep checking whether the condition is true or false and act accordingly (like a parent who keeps watching you to make sure you finish your homework before allowing you to fire up the Xbox or PlayStation). Now your program keeps checking to see whether the Player sprite is touching the Ground sprite from the instant the Green Flag button is pressed until the collision causes the STOP ALL block to end the game.

Since you will need the same code on the Pipe sprite, you can save time by copying the code blocks.

Copy blocks from Ground to Pipe

Click the top block (WHEN GREEN FLAG CLICKED) and drag the blocks from the Scripts Area directly onto the Pipe sprite icon beneath the Stage.

image2.jpg

Once you release the mouse/trackpad button, you should see the original code snap back into place on the Scripts tab. If you click the Pipe sprite icon beneath the Stage, you should find the code has been copied there.

image3.jpg

If the new blocks are overlapping the previous code, click and drag the top block to the right or beneath the other code.

image4.jpg

Dragging the top block moves all the connected blocks. If you drag a middle block, only the blocks snapped beneath it stay connected.

Click the Green Flag button, and you should find that the game ends when the Player sprite touches the Pipe sprite or the Ground sprite.