GameSpark/Tutorials Open editor ↗
GameSpark · Lesson 4

Move with the keyboard

Lesson 1 nudged a circle with the arrow keys. Here we go deeper: keeping it on screen, and telling apart a key that is held from a key that was just pressed.

1. Held keys: key()

key(name) is true for every frame a key is held down, which is exactly what you want for movement — hold right, keep moving right:

let x = 64;
let y = 64;
let speed = 2;

function update() {
  if (key('ArrowLeft')) {
    x -= speed;
  }
  if (key('ArrowRight')) {
    x += speed;
  }
  if (key('ArrowUp')) {
    y -= speed;
  }
  if (key('ArrowDown')) {
    y += speed;
  }
}

function draw() {
  cls(1);
  circfill(x, y, 5, 10);
}

Using separate ifs (not else if) lets two keys work at once, so pressing Up and Right together moves diagonally.

2. Stay on screen

Right now you can walk straight off the edge. mid(a, b, c) returns the middle of three numbers, which is a tidy way to clamp a value into a range — here, keeping the circle’s center between 5 and 122 so its 5-pixel radius never leaves the 128-wide screen:

function update() {
  if (key('ArrowLeft')) {
    x -= speed;
  }
  if (key('ArrowRight')) {
    x += speed;
  }
  if (key('ArrowUp')) {
    y -= speed;
  }
  if (key('ArrowDown')) {
    y += speed;
  }

  x = mid(5, x, 122);  // clamp to [5, 122]
  y = mid(5, y, 122);
}

3. One-shot actions: keyp()

Movement wants key, but some actions should happen once per press, no matter how long you hold — jumping, shooting, teleporting. That is keyp ("key pressed"). Compare the two:

function update() {
  // held: fires every frame the key is down
  if (key('ArrowRight')) {
    x += speed;
  }

  // pressed: fires exactly once, on the frame you press it
  if (keyp(' ')) {
    x = 64;  // space snaps back to center
  }
}

If you used key(' ') for the snap-back, holding space would pin the circle to the center forever. keyp fires just once, so each tap does one thing.

🎯

Try it: use keyp('ArrowUp') so a tap hops up by 20 instead of gliding. Swap the circle for a sprite with spr(0, x, y) and flip it to face the way it moves (see Render a sprite).

What you learned