In this exercise, you will learn how to implement player movement for the spaceship in Space Invaders. We'll use the left and right arrow keys to control the spaceship's horizontal movement.
Step 1: Creating the Player Sprite
1 Create a new sprite for your spaceship.
2 Position the spaceship at the bottom of the screen.
Step 2: Implementing Movement
1 Add the following script to your spaceship sprite:
when green flag clicked
forever
if <key [left arrow v] pressed?> then
change x by (-5)
end
if <key [right arrow v] pressed?> then
change x by (5)
end
end
This script continuously checks if the left or right arrow keys are pressed and moves the spaceship accordingly.
Step 3: Limiting Movement
To prevent the spaceship from moving off-screen, we need to add boundary checks.
when green flag clicked
forever
if <key [left arrow v] pressed?> and <(x position) > (-230)> then
change x by (-5)
end
if <key [right arrow v] pressed?> and <(x position) < (230)> then
change x by (5)
end
end
This updated script checks the spaceship's position before moving, ensuring it stays within the screen boundaries.