Build a keyboard-controlled sprite
In this guide you’ll build a sprite that the player steers with the arrow keys and that bounces off the edges of the stage. We’ll add behavior one step at a time.
Step 1 — Point and move on key press
Section titled “Step 1 — Point and move on key press”Start by turning the sprite to face a direction and stepping forward whenever an arrow key is pressed.
whenKeyPressed("right arrow", () => { setDirection(90); move(10);});
whenKeyPressed("left arrow", () => { setDirection(-90); move(10);});setDirection points the
sprite; move steps it forward in
that direction.
Step 2 — Add up and down
Section titled “Step 2 — Add up and down”whenKeyPressed("up arrow", () => { setDirection(0); move(10);});
whenKeyPressed("down arrow", () => { setDirection(180); move(10);});Step 3 — Keep the sprite on screen
Section titled “Step 3 — Keep the sprite on screen”Add a green-flag loop that bounces the sprite back whenever it reaches an edge.
whenGreenFlag(() => { forever(() => { ifOnEdgeBounce(); });});ifOnEdgeBounce flips the
sprite’s direction when it touches the edge of the stage.
Where to go next
Section titled “Where to go next”Try the Move with the arrow keys cookbook for a position-based alternative, then experiment with the step size and direction values.