Skip to content

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.

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.

whenKeyPressed("up arrow", () => {
setDirection(0);
move(10);
});
whenKeyPressed("down arrow", () => {
setDirection(180);
move(10);
});

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.

Try the Move with the arrow keys cookbook for a position-based alternative, then experiment with the step size and direction values.