Gravity in Games Lesson

Chapter One

Gravity in a game is usually simulated by changing vertical velocity over time. The object does not simply jump to the ground. Instead, gravity adds downward speed, and that speed changes the object’s position.

Chapter Two

This creates motion that feels more natural because the object accelerates as it falls. Jumping uses the same idea in reverse by giving the object an upward velocity first.

Code Runner Challenge

Gravity in Games Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Gravity in Games Lesson

const player = {
  y: 40,
  velocityY: 0,
  onGround: false
};

const gravity = 0.7;
const groundY = 180;

player.velocityY = player.velocityY + gravity;
player.y = player.y + player.velocityY;

if (player.y >= groundY) {
  player.y = groundY;
  player.velocityY = 0;
  player.onGround = true;
}

console.log(player);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Chapter Three

Gravity changes velocity, and velocity changes position. The ground check resets the player when the falling position reaches the floor.