Hardware Reference
In-Depth Information
Example 3: A Simple Game
Using Scratch for simple animation is one thing, but the software also allows users to read
inputs from the keyboard to introduce interactivity. By combining some simple animation
controls to the previously described program, you can create a simple game—and, at the
same time, introduce the concepts of sprite collision, if statements and input.
For this example, start a new Scratch project—remembering to save the previous example, if
you haven't already done so—and begin by dragging a move 10 steps block to the Scripts
area. his time, rather than telling the code blocks to execute when the lag icon is clicked, go
to the Control block palette and drag a when space key pressed block above the move
block.
As the name suggests, the when space key pressed block looks for input from the
user—in this instance, the spacebar being pressed—and uses that as the trigger for execut-
ing a list of blocks. he block works at any time—if you press the spacebar now, the sprite
will obey its instructions and move 10 steps to the right.
he when space key pressed block also difers from the when [flag icon] clicked
block in another important way: it can be customised. Click the down-arrow button next to
the word space to see a list of all the keys the block can watch, and then select right
arrow from the list to change the block into a when right arrow key pressed block.
A game in which the player can move in only one direction isn't much fun, so drag a new
when space key pressed block into the Scripts area. his can't link to the existing block
list—you can only have a single trigger block—so start a new list somewhere further down.
As before, use the down-arrow button next to the word space to customise the block, turn-
ing it into a when left arrow key pressed block. Finally, switch the block palette back
to Motion mode and connect a move 10 steps block beneath the new when left arrow
key pressed block before changing it to read move -10 steps .
If you press the left and right arrow keys now, you'll see that the cat moves according to your
input (see Figure 10-7): pressing the left arrow moves the cat 10 steps to the left (although,
as far as Scratch is concerned, it's moving minus 10 steps to the right), and pressing the right
arrow moves the cat 10 steps to the right.
Search WWH ::




Custom Search