Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

The Game Loop

3 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 7 deck

The Game Loop
Fullscreen for presentation · Print / PDF for a handout
1 / 3
Lesson

The Game Loop

Managing multiple game objects simultaneously.

The Game Loop

Creating a Game Loop

A game loop extends the animation loop concept to handle multiple objects — updating and drawing each in sequence every frame.

// Array holds all active game objects
const gameObjects = [
  new Player(50, 50, 11, 'red', ctx),
  new Enemy(200, 100, 10, 'purple', ctx),
  new Enemy(300, 100, 10, 'green', ctx),
];

function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Update phase
  gameObjects.forEach(obj => obj.update());

  // Draw phase
  gameObjects.forEach(obj => obj.draw(ctx));

  requestAnimationFrame(gameLoop);
}

gameLoop();
ConceptDetail
Array of objectsStore all game entities in one array for easy iteration.
forEach updateCall update() on every object before any drawing occurs.
forEach drawAfter all updates, draw all objects in the correct order.
ScalabilityAdd or remove objects from the array without changing the loop.
The Game Loop

Activity — complete the code

Complete the game loop that manages multiple objects.

const gameObjects = [
new Player(50, 50, 11, "red", ctx),
new Enemy(200, 100, 10, "purple", ctx),
];
 
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
 
// Update phase — update all first
gameObjects.(obj => obj.update());
 
// Draw phase — then draw all
gameObjects.(obj => obj.draw(ctx));
 
(gameLoop);
}
 
gameLoop();