A Programmer's Guide to Scratch 3
Written by Lucy Black   
Monday, 27 April 2020
Article Index
A Programmer's Guide to Scratch 3
Hello World
Bounce a ball demo
Expressions and Variables
Where to Scratch next?

Expressions and variables

It would be nice if the ball took a different path each time it was run and this can be achieved by setting it to a random rotation.

To do this you need to select the Operator palette and select the pick random block.

Now to make this work we have to do something new - we need to drag an expression into a slot within a block that until now has held a constant. This can be tricky, especially the first time you do it. As you drag the block over the slot holding the constant notice that when you have the right position it changes its appearance showing you that you have selected it. If you then drop the block it will cause the slot to enlarge to accommodate it.

If you miss then the block will sit on top of the block you are trying to put it into to. 

 

expression3

 

You can now select the default 10 and change it to 45. Yes getting a random value is this easy.

The final program is:

bounce23

 

If you now run the program you will find that the ball moves off at a different angle each time you click the green flag.

Expressions are part of the final big programming idea - variables.

A variable is a named entity in which you can store a value for later use. More generally a variable is something that stores a value which could be the result of an expression. A variable can also be included in an expression where it is treated as the value it stores.

Scratch lets you create variables - as many as you need.

For example suppose we need to keep the rotation angle for later use then we could use a variable that we might well call Rot to store the result of the random number generator.

To do this select the Variables palette and click Make a variable. In the dialog box that appears enter Rot and select For this sprite only.

 

variable3

 

In Scratch variables can be local to a sprite i.e. a property of the object or they can be global.

Once you have created a variable a set of variable specific blocks allowing you to manipulate the variable are created.

 

rot3

 

To set Rot to a random value we simply drag-and-drop the Set Rot to block into the script and then drag-and-drop the pick random block into the to slot of the block. Finally to use the value stored in Rot we drag the Rot block into the expression slot in the turn to block:

 

bounce33

 

If you run this program you will see the ball bounce in exactly the same way as before - only now you are using a variable so that the random number could be used more than once if you wanted to. 

<ASIN:1840786124>

<ASIN:1593275315>



Last Updated ( Monday, 27 April 2020 )