Welcome to this complete, in-depth tutorial where you will learn how to build a fully functional racing game using only HTML, CSS, and JavaScript — all inside a single file.
This guide is intentionally detailed and beginner-friendly. Even if you are new to JavaScript game development, you will understand every single step.
Before writing code, let's understand how this game works. The player controls a red car that can move left and right. Enemy cars spawn from the top and move downward. If the player collides with an enemy car, the game ends. The score increases over time.
This game uses a technique called requestAnimationFrame which creates smooth animations in the browser.
Click inside the game to start.
Click Here To Start
Use Arrow Keys To Move
First, we select our main HTML elements using JavaScript. This allows us to manipulate them dynamically.
We will select:
We create a player object that stores:
We listen for keydown and keyup events. When arrow keys are pressed, we update a keys object. This lets us continuously move the car while a key is held.
To simulate movement, we create white dashed lines and move them downward. When they go off-screen, we reposition them to the top.
Enemy cars spawn at random horizontal positions. They move downward. If they pass the screen, they respawn at the top.
We use bounding box collision detection. If rectangles overlap, the game ends.
The heart of the game is requestAnimationFrame. It updates: