Free Trial

Chapter 2

How to Control your Sprites with Keyboard.

In this exercise, we will explore how to use simple conditional statements to create keyboard control for the sprites.

Conditionals are fundemental building blocks of a program as it allows the computer to make decisions.

In coding, most of the time we will want a particular set of codes to be executed only if certain conditions are met.

In this exercise, we will explore how to create conditional logic with the use of the ‘IF’ statement.

Duration: 15 mins

introduction to scratch programming

What You Need

1 x Laptop/PC


If Code Block

The If code block ONLY allows codes to work if the condition is met.

if code block

Codes nested in the If code block is only executed when the conditions are met (true).

In this example, you can see that the forever loop is always running the if block (constantly checking if the keyboard right arrow is being pressed).

If the right arrow is pressed, then the code "change x by 10" will be carried out and move the sprite to the right by 10 steps.

Try this example out and see if you can move the sprite yourself.

conditionals code block keyboard move right

Up Down Left Right

Now we have coded the sprite to move right as per our command, we shall move on to code it to move left, up and down.

Note that left-right movement is referred to X and up-down movement is referred to Y.

For moving left and down, remember to put negative steps (-).

Try out the code and see it for yourself. Note: remember to set the sprite rotation style to left-right direction only. rotation style left right

keyboard control

Point in Direction

Notice that when you move sprite using the code above, the sprite will moonwalk when the sprite is moving left?

To make the movement more natural, we need to point the sprite in the correct direction before moving.

The Point in Direction code block can point the sprite in the specified direction.

1) 90 means to the right
2) -90 means to the left

Try modifying the codes and play again. You should be able to fully control the movement of the sprite with your keyboard now.

Keyboard movement control is essential for making games :)

point in direction

Well Done!

Learn about Music and Sound in the next chapter!