LEARN · PRACTISE · DISCOVER
Making Decisions with If Then
Games need to make decisions. If the player touches a coin, add a point. If the player touches a monster, the game is over. In coding, decisions are made with conditionals. In this lesson you will use if then blocks to make your sprites react to what is happening.
The if then block
The if < > then block is in the Control category. It has a pointed, six-sided space for a condition. A condition is a question with a yes or no answer, like “Am I touching the mouse pointer?”
If the answer is yes (true), the blocks inside run. If the answer is no (false), they are skipped.
Conditions come from Sensing
The pointed blocks in the Sensing category are conditions:
| Condition block | Asks |
|---|---|
touching (mouse-pointer)? | Is the sprite touching the mouse? |
touching (Apple)? | Is the sprite touching the Apple sprite? |
touching color [red]? | Is the sprite touching the colour red? |
key (space) pressed? | Is the space key being pressed? |
Always keep checking
An if block only checks once, at the moment it runs. To keep checking all the time, put it inside a forever loop.
when green flag clicked
forever
if <touching (mouse-pointer)?> then
say (That tickles!) for (1) seconds
end
endNow, whenever you move the mouse over the sprite, it says “That tickles!”.
If then else
if < > then ... else ... gives two choices. One set of blocks runs if the answer is yes, and the other runs if the answer is no.
Example
Aisha made a traffic-light game. Her car sprite checks the colour it is touching:
when green flag clicked
forever
if <touching color [red]?> then
say (Stop!)
else
move (5) steps
end
endWhen the car reaches a red line on the road, it stops and says “Stop!”. Otherwise, it keeps driving.
Smooth movement with if
Earlier you used when key pressed for movement. A smoother way, often used in games, is to check keys inside a forever loop:
when green flag clicked
forever
if <key (right arrow) pressed?> then
change x by (5)
end
if <key (left arrow) pressed?> then
change x by (-5)
end
endThis makes the sprite glide smoothly while you hold a key. You will use this in your final game.
Common bug: the check happens only once
If your if block never seems to work, check that it is inside a forever loop. Without the loop, Scratch checks the condition only once, right when the green flag is clicked, and then never again.
Key takeaways
- Conditionals let code make decisions.
- A condition is a yes or no question, often from the Sensing blocks.
- Put
ifinsideforeverto keep checking all the time. if then elsechooses between two sets of blocks.
Practice
Make a cat sprite that says “Meow!” whenever it touches a ball sprite, and says nothing otherwise. Use a forever loop.
Answer: when green flag clicked, forever, and inside it if <touching (Ball)?> then with say (Meow!), else with say () (an empty say block clears the bubble).