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

The Game Loop

Managing multiple game objects simultaneously.


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.

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

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();