3. Aim in the Right Direction
In this video, you will program the ball sprite to rotate when the user presses the arrow keys. Then, the user will be able to aim the ball!
First, make the ball sprite turn left when the left arrow key is pressed. To do this, from the “motion” menu, drag out a “turn left” block. The ball sprite should turn left *if* it senses the user pressing the left key. From the “control” menu, place an “if” block around the “turn left block.” Then, from the sensing menu, place a “key pressed” block inside the "if" block. From the dropdown, select “left arrow key.” Click the code, then press the left arrow key. Nothing happens. That’s because this code only asks once if the arrow key is pressed.
Since you weren’t pressing the left arrow key exactly when you ran the code, nothing happened. To program the ball sprite to keep asking if the user is pressing the left arrow key, put this "if" block below your first "if" block *inside* the "forever" loop.
Click the "forever" loop again to run the program.
Now press the left arrow key. The ball sprite turns left! Press the spacebar, and the ball sprite moves in that new direction until it touches the edge of the screen. This is looking good! Now that you know this code works, you can use similar code to turn the ball sprite right. From the motion menu, drag out a “turn right” block. Then, from the control menu, place an“if” block around the “turn right” block. Next, from the sensing menu place a “key pressed” block inside the “if” block, then click the dropdown and select “right arrow key.” Finally, place this "if" block inside the forever loop, and test the code by clicking on it again. When you press the left arrow, the ball sprite turns left. When you press the right arrow, the ball sprite turns right. When you press the spacebar, the ball sprite moves until it touches an edge, and the loop keeps checking for each of these conditions over and over again.
The ball sprite has to sense a lot of things in its environment to work - whether the user is pressing the left arrow key, the right arrow key, or the spacebar, and whether the ball sprite is touching the edge. This is similar to the way you use your senses! You're constantly checking for and receiving input from your eyes, ears, nose, and skin, and you do things based on that input. Wrap this step up by adding a “when flag clicked” event block on top of the code stack.
Here's the game plan: Make the ball sprite turn left and right when the arrow keys are pressed using “if” “key pressed” “turn left” and “turn right” blocks. Then, add a “when flag clicked” block to the top of the block stack. The next video will program the receivers to catch the ball.