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();
| Concept | Detail |
|---|---|
| Array of objects | Store all game entities in one array for easy iteration. |
| forEach update | Call update() on every object before any drawing occurs. |
| forEach draw | After all updates, draw all objects in the correct order. |
| Scalability | Add 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 firstgameObjects.(obj => obj.update());// Draw phase — then draw allgameObjects.(obj => obj.draw(ctx));(gameLoop);}gameLoop();