Moving Left and Right

1.  We are going to begin a new script to make our Sprite move left and right. Click and drag a “when space key pressed” block from the Events category in the Block Palette into the Code Area.


This means that whatever code we add underneath this new Events block will run when you press the space key and it will not run when the Green Flag is pressed like the other script.

2. Click on the drop-down menu in the “when space key pressed” block and select the “right arrow”. Now the code you add underneath this keyboard input Events block will run only when you press the right arrow key on your keyboard.


3. Go to the dark blue Motion category in the Blocks Palette and select the “change x by” block. Drag this block onto the Code Area and snap it underneath the “when right arrow pressedEvents block. The “change x by 10” block tells your Sprite to go right along the x-axis because the number is increasing by 10, meaning it is moving your sprite to a larger x-coordinate. Since we’ve attached this Motion block to the right arrow keyboard input, everytime you press the right key your sprite will move 10 steps to the right.


4. Now we will follow the same steps to code the Sprite to move to the left. Click and drag another “when space key pressed” block from the Events category in the Block Palette into the Code Area.


5.  Click on the drop-down menu in the “when space key pressed” block and select the “left arrow”. Now the code you add underneath this Events block will run only when you press the left arrow key on your keyboard.


6. Go to the dark blue Motion category in the Blocks Palette and select another “change x by” block. Drag this block onto the Code Area and snap it underneath the “when left arrow pressedEvents block.


7. Now we need to change the “change x by 10Motion block to move the Sprite to the left. Click on the white input bubble on the duplicated “change x by 10” block and change this number to -10. This will tell your Sprite to move to the left along the x-axis because the number is getting smaller. Now when you press the left arrow on your keyboard, your Sprite will move 10 steps to the left along the x-axis to a new, smaller x-coordinate.


8. Your Code Area should now have three Event blocks with code under each block like the image below:


9. Test your code! Press the Green Flag and then use the left and right arrows on your keyboard to move the Sprite left and right!



Views
1 Total Views
1 Members Views
0 Public Views
Share on Social Networks
Share Link
Share by mail

Please login to share this webpage by email.