Think about a game that you’ve played in the past. Chances are there was a time that your character had to interact with another object. Maybe it’s when you had to collect rings as Sonic, attack a Like Like in Legend of Zelda, or gather materials in Minecraft.
Many good hours were spent punching trees
To determine that your character has touched (or collided) with another object, we use a process called collision detection. Some game engines have built-in collision detection. Scratch, in fact, has this functionality in its touching
blocks below:
A sprite in Scratch can sense if it’s touching another sprite, the edge of the screen, the mouse, or even a color!
In other languages, a wee bit of math is often required to make this happen. Specifically, collision detection is often achieved by checking if the coordinates (x, y) of one object are close enough to another!
Perhaps we want a game to end if two objects touch each other. To do this, we’ll have to end the game loop once we detect a collision. There are two ways to do this in Scratch that depend on how you set up your game loop:
In these examples the pink Move
and End Game
blocks are custom blocks that I made elsewhere off screen that preform the tasks they’re named after. This process of creating custom blocks or functions to simplify main chunks of code is called abstraction. It’s something you’ll get much more used to as you further study computer science.
In both of these examples, this sprite will continue being able to move until it touches the edge of the screen; at that time, the game will end.
Let’s make a game where the main character’s sprite needs to move to a goal (another sprite of your choosing) to win the game. To do this, start with your code from Move so that we will have character movement. Then, we’ll add a new sprite that will contain the code for ending the game with a victory!
If done with the main mission, add obstacles that the main sprite can’t touch without losing the game!