Coding Academy home

Help & Lessons / Moving Your Shape

Moving Your Shape

Hopping Like Frogger

keys.left/right/up/down/space are true on every single frame a key is held — great for smooth, sliding movement, but not for a game like Frogger, where one press should mean one hop, no matter how long you hold the key down.

For that, use the "just pressed" versions instead: keys.leftPressed, keys.rightPressed, keys.upPressed, keys.downPressed, keys.spacePressed. Each one is true for exactly one frame — the instant the key first goes down — then false again even while it's still held, until you let go and press it again.

export function update(self, keys) {
    if (keys.leftPressed) self.setX(self.getX() - 40);
    if (keys.rightPressed) self.setX(self.getX() + 40);
    if (keys.upPressed) self.setY(self.getY() - 40);
    if (keys.downPressed) self.setY(self.getY() + 40);
}

Hold the right arrow down for as long as you like — this shape moves exactly 40 pixels once, and waits for you to press again before it moves any more. Pick a step size (40 here) that matches whatever grid your game is on.

Same idea, different key: keys.left is "is it down right now" (check it every frame, for sliding). keys.leftPressed is "did it just go down" (check it once per press, for hopping).