In this video,
you will program the ball sprite to move
when the spacebar is pressed.
First, click on the ball sprite.
From the motion menu,
drag out the move ten steps block.
Next, program the ball to repeat moving
until it touches the edge of the stage.
From the control menu,
place a repeat until loop around the move ten steps block.
In the repeat until block,
there's a space to tell the blocks inside it
when to stop repeating.
In this case,
the block should stop repeating when they sense
that the ball sprite is touching the edge of the stage.
From a sensing menu,
drag out the touching block
and place it inside the repeat until block.
Click the drop down and select edge.
Click on the code to test it.
The ball sprite should move
until it touches the edge of the screen then stop,
and it does.
To make the sprite return to its starting location
every time the code is run,
you'll use a go to XY block.
First, though, drag the sprite to its starting position.
The values in the go to XY block will automatically update
in the menu based on the sprite's position.
Then drag the go to XY block above the repeat loop.
Click the code.
The sprite moves until it touches the edge of the stage.
Click the code again.
It begins in its starting location,
then moves until it touches the edge of the screen.
To make this keep happening for the entire game,
place a forever loop from the control menu
around the code.
Click on the code again.
The ball sprite goes to its start location,
then moves to the edge of the screen,
then returns to its start location over and over
and over again.
Next control when the ball sprite starts moving
so that it doesn't keep looping uncontrollably.
First, click the stop sign.
To make the ball move only when it senses
that the spacebar has been pressed,
go to the control menu.
Choose an if block and place it around the repeat until loop
under the go to block.
Then go to the sensing menu and place a key press block
inside the if.
Click the drop down and select spacebar.
Now the code reads,
forever go to the starting location.
If the spacebar is pressed,
repeat moving until touching the edge.
Once touching the edge,
run the loop again and return to the starting location.
Test the code by clicking on it,
then pressing the spacebar.
So far so good.
Here's the game plan.
Make the ball sprite move
until it touches the edge of the screen
using move, repeat until, and touching edge blocks.
Give the ball sprite a starting location
using the go to block.
Make the ball sprite repeat these actions
using a forever block.
And finally, make the ball sprite move
only if the user presses the spacebar
with if and key pressed blocks.
In the next video,
you will learn how to control the ball sprites direction.
Sign in to track your progress and earn badges