GameSpark/Tutorials Open editor ↗
Add gravity · Step 1 of 3

Falling and jumping

Gravity is the same trick as velocity (from the Bounce lesson) with one extra line: every frame, nudge the downward velocity a little more. That steady nudge is what makes a jump arc up, slow, and fall back — the feel of real gravity.

1. Falling

Keep two variables: a position y and a vertical velocity dy. Each frame, add a small constant to dy (that is gravity), then add dy to y. Because dy keeps growing, the fall speeds up:

let y = 40;
let dy = 0;

const GRAVITY = 0.3;

function update() {
  dy = dy + GRAVITY;   // gravity makes the velocity grow
  y = y + dy;          // velocity moves the position
}

function draw() {
  cls(1);
  circfill(64, y, 6, 12);
}
💡

Notice dy is never a fixed speed — it accelerates. Adding a constant to the velocity each frame is exactly what acceleration means. A bigger GRAVITY feels heavy and snappy; a smaller one feels floaty, like the moon.

2. Land on the floor

Right now the circle falls off the bottom forever. Pick a floor height, and when y passes it, snap y back to the floor and set dy to 0 so it stops:

let y = 40;
let dy = 0;

const GRAVITY = 0.3;
const FLOOR = 110;

function update() {
  dy = dy + GRAVITY;
  y = y + dy;

  if (y > FLOOR) {
    y = FLOOR;   // sit exactly on the floor
    dy = 0;      // stop falling
  }
}

function draw() {
  cls(1);
  line(0, FLOOR + 6, 128, FLOOR + 6, 5);
  circfill(64, y, 6, 12);
}
⚠️

Setting dy = 0 matters as much as fixing y. If you only snap y back but leave dy growing, the next frame yanks the circle straight through the floor again.

3. Jump

A jump is just a sudden upward velocity — a negative dy, because y grows downward on screen. Gravity then does the rest, slowing the rise and pulling it back down. Only allow a jump when standing on the floor, so you can’t jump in mid-air:

const JUMP = -6;

function update() {
  dy = dy + GRAVITY;
  y = y + dy;

  if (y > FLOOR) {
    y = FLOOR;
    dy = 0;
  }

  if (keyp(' ') && y === FLOOR) {
    dy = JUMP;   // launch upward
  }
}

That is the whole recipe: gravity grows dy, dy moves y, the floor stops it, and a keypress kicks dy upward. Send it to the editor and tune the three constants until the jump feels right.

🎯

Try it: make GRAVITY smaller for a floaty moon-jump, or JUMP more negative for a higher leap. Use key(' ') instead of keyp(' ') and feel the difference — held-down flying versus one jump per press (see the Input lesson).

What you learned