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 10steps” block. Next, program the ball to *repeat* moving*until* it touches the edge of the stage. From the “control” menu, place a “repeatuntil” loop around the “move 10 steps” block.
In the “repeat until” block there’s a space to tell the blocks inside it whento stop repeating. In this case, the blocks should stop repeating when they sense thatthe ball sprite is touching the edge of the stage. From the "sensing" menu, drag out the“touching” block, and place it inside the “repeat until” block. Click the dropdown,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 itdoes. To make the sprite return to its startinglocation every time the code is run, you'll use a "go to x y" block. First, though, dragthe sprite to its starting position. The values in the "go to x y block" will automaticallyupdate in the menu based on the sprite's position. Then, drag the "go to x y" block above therepeat loop. Click the code. The sprite moves until ittouches 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. Pretty neat!
To make this keep happening for the entire game, place a forever loop from the controlmenu around the code. Click on the code again. The ball sprite goesto 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 startsmoving, 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 tothe 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 pressed”block inside the “if." Click the dropdown, 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, andreturn to the starting location.” Test the code by clicking on it, then pressingthe 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,” “repeatuntil,” and “touching edge” blocks. Give the ball sprite a starting location usingthe “go to” block. Make the ball sprite repeat these actionsusing a “forever” block. And finally, make the ball sprite move onlyif the user presses the spacebar with “if” and “key pressed” blocks.
In the next video, you will learn how to control the ball sprite’s direction.