How a browser game works: the game loop explained
When you play a game like Space Shooter, it feels like everything happens at once: the stars move, aliens fly, lasers shoot and explosions sparkle. Under the hood, the computer is actually doing one small thing again and again, about 60 times every second. That one small thing is called the game loop.
The three steps of the game loop
Every frame (one picture on the screen), the game does three things in order:
- Read the input. Which keys are pressed? Did you tap the screen?
- Update the world. Move the ship, move each alien a little, move each laser up, and check whether anything crashed into anything.
- Draw everything. Clear the screen and draw every object in its new position.
Then it starts again. Because it happens so fast, your eyes see smooth movement, just like a flip-book.
Drawing on a canvas
Most of the games on the hub draw on an HTML element called a <canvas>. Think of it as a blank sheet of paper that JavaScript can paint on. To draw a spaceship, the game tells the canvas: "move the pen here, draw a line there, fill it with this colour". Every frame, the canvas is wiped clean and painted again.
Moving things
Every object has a position, an x (left and right) and a y (up and down). To move an alien to the right, the game adds a little to its x each frame. To make the dinosaur in Dino Run jump, the game gives it an upward speed, then gravity pulls a little bit of that speed away every frame until it falls back down. That's the same physics you learn about in science class.
Checking for crashes
How does the game know your laser hit an alien? It checks whether their boxes overlap. If the laser's x and y are inside the alien's box, it's a hit. This is called collision detection, and almost every game uses it, from Brick Smash to Subway Runner.
Keeping it fair on every computer
Some computers are faster than others. If the game moved things by the same amount every frame, it would run faster on a fast computer. To fix this, good games measure how much time passed since the last frame and move things by that much. That way the game runs at the same speed everywhere.
Try it yourself
If you'd like to build your own game, read our next article: Make your first game in 30 lines of JavaScript.