The Game Loop and Animation
Build a game loop with requestAnimationFrame, move objects with velocity, bounce them off walls and add gravity for a jump that feels right.
Welcome back!
Step 1 of 10Learn
Movies are fast pictures
A cartoon is a stack of still drawings shown quickly. Games work the same way. Many times per second, the game does three things:
- Update: change the state (move the player, move enemies, check collisions).
- Draw: clear the canvas and paint everything at its new position.
- Repeat.
Each picture is a frame, and this cycle is the game loop. Most screens refresh about 60 times per second, so a smooth game draws about 60 frames per second (fps), one every 16.7 milliseconds or so.
In the browser, you don't use a while loop for this (remember, that would freeze the page). You use requestAnimationFrame, which asks the browser to call your function right before the next screen refresh:
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);Each time gameLoop runs, it schedules itself again for the next frame. Between frames, the browser is free to handle clicks, key presses and everything else, which keeps the page responsive. Browsers also pause it automatically when the tab is hidden, saving battery.
Step 2 of 10Practice · Put in order
Arrange the parts of one pass through a typical game loop.
Drag the items, or use the arrow buttons, to put them in order.
- Clear the canvas
- Update positions and game state
- Read the current input, such as which keys are held
- Draw every object at its new position
- Check for collisions and apply the results
- Ask requestAnimationFrame for the next frame
Step 3 of 10Practice · Diagram
The game loop, about 60 times a second
Which step keeps the loop going without freezing the page?
Tap the shape that answers the question, then press Check.
- Update the state
Move the player and enemies, check collisions.
- Clear the canvas
Wipe last frame so nothing smears.
- Draw everything
Paint every object at its new position.
- requestAnimationFrame
Ask the browser to call the loop again before the next repaint.
Step 4 of 10Learn
Velocity and bouncing
To move a ball, give it a position and a velocity: how far it moves per frame on each axis.
let ball = { x: 100, y: 80, vx: 3, vy: 2, r: 10 };
function update() {
ball.x += ball.vx;
ball.y += ball.vy;
}Every frame the ball moves 3 pixels right and 2 pixels down. At 60 fps, that's 180 pixels per second sideways.
Without walls, it would drift off the canvas forever. To bounce, check whether the ball has reached an edge and flip the sign of the matching velocity:
if (ball.x + ball.r > canvas.width || ball.x - ball.r < 0) {
ball.vx = -ball.vx;
}
if (ball.y + ball.r > canvas.height || ball.y - ball.r < 0) {
ball.vy = -ball.vy;
}Notice the radius in the checks. Since the ball's position is its center, the right edge of the ball is at x + r. Checking only ball.x > canvas.width would let half the ball disappear into the wall before bouncing.
Flipping the sign keeps the speed but reverses the direction, like a perfect bounce. Multiply by something like -0.8 instead and the ball loses a bit of energy with every bounce, which looks more realistic for a bouncing rubber ball.
Step 5 of 10Practice · Work it out
A ball has x = 100 and vx = 4. Assuming it hits no walls, what is its x position after 30 frames?
Step 6 of 10Learn
Gravity and jumping
Gravity in games is a tiny trick: instead of changing the position by a constant amount, change the velocity a little every frame.
const GRAVITY = 0.5;
function update() {
player.vy += GRAVITY; // speed up downward
player.y += player.vy; // move
if (player.y > GROUND_Y) { // landed
player.y = GROUND_Y;
player.vy = 0;
player.onGround = true;
}
}Because y points down, a positive vy means falling, and adding gravity makes the fall faster and faster, just like real objects.
A jump is one instant kick upward, which means a negative vy:
if (jumpPressed && player.onGround) {
player.vy = -10;
player.onGround = false;
}On the first frame the player moves up 10 pixels, then 9.5, then 9, and so on as gravity eats away the upward speed. When vy reaches 0, the player is at the top of the jump; then it turns positive and the player falls back down. The result is a smooth curve, a parabola, without writing any curve math yourself.
The onGround check prevents a classic bug: without it, players can press jump in mid-air and fly forever.
Step 7 of 10Explore
Jump explorer
The curve shows how high the player is above the ground (in pixels) for each frame after pressing jump. Change the jump strength and gravity to tune how the jump feels.
- Approximate peak height
- 100 px
- Approximate frames in the air
- 40
- Approximate time in the air at 60 fps
- 0.67 s
Step 8 of 10Note
Step 9 of 10Practice · Code challenge
Write bounceX(ball, width) for a ball object with properties x, vx and r (radius). If the ball's right edge is past width, or its left edge is past 0, reverse vx. Return the ball's vx after the check.
bounceX({ x: 475, vx: 3, r: 10 }, 480)bounceX({ x: 5, vx: -2, r: 10 }, 480)bounceX({ x: 240, vx: 3, r: 10 }, 480)bounceX({ x: 465, vx: 4, r: 10 }, 480)
Step 10 of 10Practice · Choose one
A player has vy = -10 and gravity adds 0.5 to vy every frame. After how many frames does the player reach the top of the jump, where vy becomes 0?
Lesson complete!