🎬 Game Loop and Animation
Master the game loop, delta time, frame timing, and smooth animations for professional games!
Your Progress
0 / 9 completed📚 Sections
Understanding the Game Loop
Section 1 of 9
The game loop is the heartbeat of every game. It's a continuous cycle that updates game logic and renders graphics many times per second, creating the illusion of movement and interactivity. **The Three Pillars:** 1. Process Input - Handle keyboard, mouse, touch events 2. Update - Move objects, check collisions, update game state 3. Render - Draw everything to the screen **Why Do We Need a Loop?** Games are interactive simulations that respond to player input in real-time. Unlike static programs, games need to constantly update positions, check for collisions, animate sprites, and redraw the screen. **The Classic Game Loop Pattern:** • Run continuously at a target frame rate (usually 60 FPS) • Each iteration is called a "frame" or "tick" • Smooth gameplay requires consistent timing • Must handle both fast and slow devices gracefully **Frame Rate vs Refresh Rate:** • Frame Rate: How many times your game updates per second • Refresh Rate: How many times the monitor updates per second • Target: 60 FPS to match most monitors (16.67ms per frame)
Code Example:
// Basic game loop structure
function gameLoop() {
// 1. Process Input
handleInput();
// 2. Update Game State
updatePlayer();
updateEnemies();
checkCollisions();
updatePhysics();
// 3. Render
clearScreen();
drawBackground();
drawPlayer();
drawEnemies();
drawUI();
// Continue the loop
requestAnimationFrame(gameLoop);
}
// Start the game
requestAnimationFrame(gameLoop);
// Simple example with a moving box
let x = 0;
function simpleLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Update
x += 2;
if (x > canvas.width) x = 0;
// Draw
ctx.fillStyle = 'blue';
ctx.fillRect(x, 100, 50, 50);
requestAnimationFrame(simpleLoop);
}💡 Tip: Try this code in your browser console (F12 → Console).