Creating a 2D Car Racing Game using HTML, CSS, and JavaScript is an exciting project that involves several components, including graphics rendering, user input handling, collision detection, and game state management. Below, you'll find a step-by-step guide along with the complete code to help you build the game based on your provided prompt.
Table of Contents
- Project Structure
- HTML Setup
- CSS Styling
- JavaScript Logic
- Final Touches
- Complete Code
Project Structure
For simplicity, we'll structure the project with three main files:
index.html – The HTML structure.
styles.css – The CSS styles.
game.js – The JavaScript game logic.
Optional assets like images and sounds can be placed in separate folders (e.g., assets/images, assets/sounds).
1. HTML Setup
We'll use the <canvas> element to render the game graphics and add additional HTML elements for the timer, leaderboard, and game messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2D Car Racing Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="game-container">
<canvas id="gameCanvas" width="400" height="600"></canvas>
<div id="ui">
<div id="timer">Time: 0.00s</div>
<div id="leaderboard">
<h3>Leaderboard</h3>
<ol id="scoresList">
<!-- High scores will be appended here -->
</ol>
</div>
<div id="game-over" class="hidden">
<h2>Game Over</h2>
<p>Your Time: <span id="finalTime">0.00</span>s</p>
<button id="restartButton">Restart</button>
</div>
</div>
</div>
<script src="game.js"></script>
</body>
</html>
Explanation:
- Canvas: The
<canvas> element with id="gameCanvas" will be used to draw the game.
- UI Elements: A timer, a leaderboard, and a game-over screen are included for user interaction and feedback.
2. CSS Styling
Here's a basic CSS setup to style the game elements. You can customize the colors, fonts, and layout as desired.
/* styles.css */
body {
margin: 0;
padding: 0;
background-color: #333;
font-family: Arial, sans-serif;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#game-container {
position: relative;
width: 400px;
height: 600px;
background-color: #555;
border: 2px solid #fff;
overflow: hidden;
}
#gameCanvas {
background-color: #222;
}
#ui {
position: absolute;
top: 10px;
left: 10px;
width: 380px;
display: flex;
justify-content: space-between;
pointer-events: none;
}
#timer {
font-size: 18px;
}
#leaderboard {
font-size: 14px;
max-height: 100px;
overflow-y: auto;
}
#game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.8);
padding: 20px;
border: 2px solid #fff;
text-align: center;
pointer-events: auto;
}
.hidden {
display: none;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
Explanation:
- Layout: The game container centers the canvas and UI elements.
- Canvas Styling: The canvas has a dark background to resemble a night race.
- UI Styling: The timer and leaderboard are positioned at the top, while the game-over screen is centered and hidden by default.
3. JavaScript Logic
The JavaScript code handles the game mechanics, including rendering, user input, obstacle management, scoring, and game state transitions.
Game Initialization
We'll set up the canvas, load assets (if any), and define the game entities like the car and obstacles.
// game.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const timerElement = document.getElementById('timer');
const leaderboardElement = document.getElementById('scoresList');
const gameOverElement = document.getElementById('game-over');
const finalTimeElement = document.getElementById('finalTime');
const restartButton = document.getElementById('restartButton');
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
// Game Variables
let gameRunning = false;
let startTime;
let elapsedTime = 0;
let highScores = [];
// Load High Scores from localStorage
if (localStorage.getItem('highScores')) {
highScores = JSON.parse(localStorage.getItem('highScores'));
updateLeaderboard();
}
// Car Object
const car = {
width: 40,
height: 70,
x: canvasWidth / 2 - 20,
y: canvasHeight - 100,
speed: 5,
dx: 0,
dy: 0,
color: 'red',
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
},
move: function() {
this.x += this.dx;
this.y += this.dy;
// Boundary Checking
if (this.x < 0) this.x = 0;
if (this.x + this.width > canvasWidth) this.x = canvasWidth - this.width;
if (this.y < 0) this.y = 0;
if (this.y + this.height > canvasHeight) this.y = canvasHeight - this.height;
}
};
// Handle Keyboard Input
const keys = {};
document.addEventListener('keydown', (e) => {
keys[e.key] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.key] = false;
});
// Obstacles Array
const obstacles = [];
const obstacleFrequency = 1500; // milliseconds
let lastObstacleTime = 0;
// Game Over Function
function endGame() {
gameRunning = false;
gameOverElement.classList.remove('hidden');
finalTimeElement.textContent = elapsedTime.toFixed(2);
saveHighScore(elapsedTime);
}
// Restart Game
restartButton.addEventListener('click', () => {
resetGame();
});
// Reset Game Function
function resetGame() {
car.x = canvasWidth / 2 - 20;
car.y = canvasHeight - 100;
car.dx = 0;
car.dy = 0;
obstacles.length = 0;
elapsedTime = 0;
timerElement.textContent = `Time: 0.00s`;
gameOverElement.classList.add('hidden');
gameRunning = true;
startTime = performance.now();
requestAnimationFrame(gameLoop);
}
// Start Game on Load
window.onload = () => {
resetGame();
};
Explanation:
- Canvas Setup: References to the canvas and its context are obtained for drawing.
- UI Elements: Timer, leaderboard, and game-over elements are accessed for updates.
- Game Variables: Flags and timers to control game state.
- High Scores: Stored in
localStorage to persist across sessions.
- Car Object: Represents the player's car with properties and methods to draw and move it.
- Input Handling: Tracks which keys are pressed for car movement.
- Obstacles: Managed in an array with a frequency to control their generation.
- Game Over: Handles ending the game, showing the game-over screen, and saving the score.
- Restart Mechanism: Allows the player to restart the game.
Car Movement
Handle the car's movement based on user input.
// Car movement inside update function
function handleInput() {
if (keys['ArrowLeft'] || keys['a'] || keys['A']) {
car.dx = -car.speed;
} else if (keys['ArrowRight'] || keys['d'] || keys['D']) {
car.dx = car.speed;
} else {
car.dx = 0;
}
if (keys['ArrowUp'] || keys['w'] || keys['W']) {
car.dy = -car.speed;
} else if (keys['ArrowDown'] || keys['s'] || keys['S']) {
car.dy = car.speed;
} else {
car.dy = 0;
}
}
Explanation:
- Input Mapping: Maps arrow keys and WASD to car movement.
- Direction Control: Sets the car's
dx and dy based on key presses.
- No Diagonal Movement: Adjustments can be made if diagonal movement is desired.
Track and Scenery
For a simple track, we'll draw lanes and maybe add some scrolling effect for the illusion of movement.
// Draw Track Function
function drawTrack() {
// Background
ctx.fillStyle = '#555';
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
// Draw Lanes
const laneCount = 3;
const laneWidth = canvasWidth / laneCount;
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
for (let i = 1; i < laneCount; i++) {
ctx.setLineDash([20, 15]);
ctx.beginPath();
ctx.moveTo(i * laneWidth, 0);
ctx.lineTo(i * laneWidth, canvasHeight);
ctx.stroke();
}
}
Explanation:
- Background: Sets the overall track color.
- Lanes: Divides the canvas into multiple lanes with dashed lines.
Obstacles Generation and Collision Detection
Obstacles like trees, rocks, or other cars are randomly generated and move towards the player to simulate movement.
// Obstacle Class
class Obstacle {
constructor(x, y, width, height, speed, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
this.color = color;
}
update() {
this.y += this.speed;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// Generate Obstacles
function generateObstacle() {
const laneCount = 3;
const laneWidth = canvasWidth / laneCount;
const lane = Math.floor(Math.random() * laneCount);
const obstacleWidth = 40;
const obstacleHeight = 70;
const x = lane * laneWidth + (laneWidth - obstacleWidth) / 2;
const y = -obstacleHeight;
const speed = 3;
const color = 'blue'; // Can randomize colors or use images
obstacles.push(new Obstacle(x, y, obstacleWidth, obstacleHeight, speed, color));
}
// Update Obstacles
function updateObstacles(deltaTime) {
obstacles.forEach((obstacle, index) => {
obstacle.update();
obstacle.draw();
// Collision Detection
if (detectCollision(car, obstacle)) {
endGame();
}
// Remove Obstacles that are off-screen
if (obstacle.y > canvasHeight) {
obstacles.splice(index, 1);
}
});
// Generate new obstacles based on frequency
if (performance.now() - lastObstacleTime > obstacleFrequency) {
generateObstacle();
lastObstacleTime = performance.now();
}
}
// Collision Detection Function
function detectCollision(rect1, rect2) {
return (
rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y
);
}
Explanation:
- Obstacle Class: Defines the obstacle's properties and methods to update position and draw itself.
- Generation: Randomly places obstacles in one of the lanes at set intervals.
- Update: Moves obstacles downward to simulate the car moving forward and checks for collisions.
- Collision Detection: Determines if the car intersects with any obstacle, triggering a game over.
Scoring and Timer
Tracks the elapsed time and updates the leaderboard.
// Update Timer
function updateTimer() {
elapsedTime = (performance.now() - startTime) / 1000;
timerElement.textContent = `Time: ${elapsedTime.toFixed(2)}s`;
}
// Save High Score
function saveHighScore(time) {
highScores.push(time);
highScores.sort((a, b) => a - b);
if (highScores.length > 5) highScores.pop(); // Keep top 5
localStorage.setItem('highScores', JSON.stringify(highScores));
updateLeaderboard();
}
// Update Leaderboard
function updateLeaderboard() {
leaderboardElement.innerHTML = '';
highScores.forEach((score) => {
const li = document.createElement('li');
li.textContent = `${score.toFixed(2)}s`;
leaderboardElement.appendChild(li);
});
}
Explanation:
- Timer: Calculates and displays the elapsed time since the game started.
- High Scores: Saves and sorts the top 5 fastest times using
localStorage.
- Leaderboard: Dynamically updates the leaderboard UI with high scores.
Game Loop
The core loop that updates and renders the game each frame.
// Game Loop
function gameLoop(timestamp) {
if (!gameRunning) return;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
drawTrack();
handleInput();
car.move();
car.draw();
updateObstacles();
updateTimer();
requestAnimationFrame(gameLoop);
}
Explanation:
- Clear Canvas: Clears the previous frame's drawings.
- Draw Track: Renders the track and lanes.
- Handle Input: Processes user inputs for car movement.
- Update Car: Moves and draws the car.
- Update Obstacles: Manages obstacle movement and collision.
- Update Timer: Refreshes the timer display.
- Loop: Continuously repeats using
requestAnimationFrame for smooth animations.
4. Final Touches
Enhancements
You can enhance the game by adding the following features:
- Customizable Car: Allow players to choose different car colors or shapes.
- Obstacle Variety: Introduce different types of obstacles with varying sizes and speeds.
- Sound Effects: Add sounds for car movement, collisions, and background music.
- Level Progression: Increase obstacle frequency or speed as time progresses to raise difficulty.
- Mobile Controls: Implement touch controls for mobile device compatibility.
Optimization
- Performance: Optimize drawing routines and limit the number of active obstacles to ensure smooth performance.
- Responsive Design: Make the canvas size responsive to different screen sizes while maintaining aspect ratio.
Complete Code
Below is the complete code for each file. Ensure that all files are in the same directory or update file paths accordingly.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=400, initial-scale=1.0">
<title>2D Car Racing Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="game-container">
<canvas id="gameCanvas" width="400" height="600"></canvas>
<div id="ui">
<div id="timer">Time: 0.00s</div>
<div id="leaderboard">
<h3>Leaderboard</h3>
<ol id="scoresList">
<!-- High scores will be appended here -->
</ol>
</div>
<div id="game-over" class="hidden">
<h2>Game Over</h2>
<p>Your Time: <span id="finalTime">0.00</span>s</p>
<button id="restartButton">Restart</button>
</div>
</div>
</div>
<script src="game.js"></script>
</body>
</html>
styles.css
/* styles.css */
body {
margin: 0;
padding: 0;
background-color: #333;
font-family: Arial, sans-serif;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#game-container {
position: relative;
width: 400px;
height: 600px;
background-color: #555;
border: 2px solid #fff;
overflow: hidden;
}
#gameCanvas {
background-color: #222;
}
#ui {
position: absolute;
top: 10px;
left: 10px;
width: 380px;
display: flex;
justify-content: space-between;
pointer-events: none;
}
#timer {
font-size: 18px;
}
#leaderboard {
font-size: 14px;
max-height: 100px;
overflow-y: auto;
}
#game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.8);
padding: 20px;
border: 2px solid #fff;
text-align: center;
pointer-events: auto;
}
.hidden {
display: none;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
game.js
// game.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const timerElement = document.getElementById('timer');
const leaderboardElement = document.getElementById('scoresList');
const gameOverElement = document.getElementById('game-over');
const finalTimeElement = document.getElementById('finalTime');
const restartButton = document.getElementById('restartButton');
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
// Game Variables
let gameRunning = false;
let startTime;
let elapsedTime = 0;
let highScores = [];
// Load High Scores from localStorage
if (localStorage.getItem('highScores')) {
highScores = JSON.parse(localStorage.getItem('highScores'));
updateLeaderboard();
}
// Car Object
const car = {
width: 40,
height: 70,
x: canvasWidth / 2 - 20,
y: canvasHeight - 100,
speed: 5,
dx: 0,
dy: 0,
color: 'red',
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
},
move: function() {
this.x += this.dx;
this.y += this.dy;
// Boundary Checking
if (this.x < 0) this.x = 0;
if (this.x + this.width > canvasWidth) this.x = canvasWidth - this.width;
if (this.y < 0) this.y = 0;
if (this.y + this.height > canvasHeight) this.y = canvasHeight - this.height;
}
};
// Handle Keyboard Input
const keys = {};
document.addEventListener('keydown', (e) => {
keys[e.key] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.key] = false;
});
// Obstacles Array
const obstacles = [];
const obstacleFrequency = 1500; // milliseconds
let lastObstacleTime = 0;
// Obstacle Class
class Obstacle {
constructor(x, y, width, height, speed, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
this.color = color;
}
update() {
this.y += this.speed;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// Draw Track Function
function drawTrack() {
// Background
ctx.fillStyle = '#555';
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
// Draw Lanes
const laneCount = 3;
const laneWidth = canvasWidth / laneCount;
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
for (let i = 1; i < laneCount; i++) {
ctx.setLineDash([20, 15]);
ctx.beginPath();
ctx.moveTo(i * laneWidth, 0);
ctx.lineTo(i * laneWidth, canvasHeight);
ctx.stroke();
}
ctx.setLineDash([]);
}
// Handle Input
function handleInput() {
if (keys['ArrowLeft'] || keys['a'] || keys['A']) {
car.dx = -car.speed;
} else if (keys['ArrowRight'] || keys['d'] || keys['D']) {
car.dx = car.speed;
} else {
car.dx = 0;
}
if (keys['ArrowUp'] || keys['w'] || keys['W']) {
car.dy = -car.speed;
} else if (keys['ArrowDown'] || keys['s'] || keys['S']) {
car.dy = car.speed;
} else {
car.dy = 0;
}
}
// Generate Obstacles
function generateObstacle() {
const laneCount = 3;
const laneWidth = canvasWidth / laneCount;
const lane = Math.floor(Math.random() * laneCount);
const obstacleWidth = 40;
const obstacleHeight = 70;
const x = lane * laneWidth + (laneWidth - obstacleWidth) / 2;
const y = -obstacleHeight;
const speed = 3;
const color = getRandomColor();
obstacles.push(new Obstacle(x, y, obstacleWidth, obstacleHeight, speed, color));
}
// Get Random Color
function getRandomColor() {
const colors = ['blue', 'green', 'yellow', 'purple', 'orange'];
return colors[Math.floor(Math.random() * colors.length)];
}
// Update Obstacles
function updateObstacles() {
obstacles.forEach((obstacle, index) => {
obstacle.update();
obstacle.draw();
// Collision Detection
if (detectCollision(car, obstacle)) {
endGame();
}
// Remove Obstacles that are off-screen
if (obstacle.y > canvasHeight) {
obstacles.splice(index, 1);
}
});
// Generate new obstacles based on frequency
if (performance.now() - lastObstacleTime > obstacleFrequency) {
generateObstacle();
lastObstacleTime = performance.now();
}
}
// Collision Detection Function
function detectCollision(rect1, rect2) {
return (
rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y
);
}
// Update Timer
function updateTimer() {
elapsedTime = (performance.now() - startTime) / 1000;
timerElement.textContent = `Time: ${elapsedTime.toFixed(2)}s`;
}
// Save High Score
function saveHighScore(time) {
highScores.push(time);
highScores.sort((a, b) => a - b);
if (highScores.length > 5) highScores.pop(); // Keep top 5
localStorage.setItem('highScores', JSON.stringify(highScores));
updateLeaderboard();
}
// Update Leaderboard
function updateLeaderboard() {
leaderboardElement.innerHTML = '';
highScores.forEach((score) => {
const li = document.createElement('li');
li.textContent = `${score.toFixed(2)}s`;
leaderboardElement.appendChild(li);
});
}
// Game Over Function
function endGame() {
gameRunning = false;
gameOverElement.classList.remove('hidden');
finalTimeElement.textContent = elapsedTime.toFixed(2);
saveHighScore(elapsedTime);
}
// Restart Game
restartButton.addEventListener('click', () => {
resetGame();
});
// Reset Game Function
function resetGame() {
car.x = canvasWidth / 2 - 20;
car.y = canvasHeight - 100;
car.dx = 0;
car.dy = 0;
obstacles.length = 0;
elapsedTime = 0;
timerElement.textContent = `Time: 0.00s`;
gameOverElement.classList.add('hidden');
gameRunning = true;
startTime = performance.now();
lastObstacleTime = performance.now();
requestAnimationFrame(gameLoop);
}
// Game Loop
function gameLoop(timestamp) {
if (!gameRunning) return;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
drawTrack();
handleInput();
car.move();
car.draw();
updateObstacles();
updateTimer();
requestAnimationFrame(gameLoop);
}
// Start Game on Load
window.onload = () => {
resetGame();
};
Running the Game
-
Folder Setup: Create a project folder and place the index.html, styles.css, and game.js files inside it.
-
Assets (Optional): If you plan to add images or sounds, create assets/images and assets/sounds folders and update the paths in the code accordingly.
-
Open the Game:
- Open
index.html in a web browser (preferably Chrome or Firefox for best compatibility).
- Use the arrow keys or WASD to control the car.
-
Gameplay:
- Navigate the car to avoid incoming obstacles.
- Survive as long as possible to achieve a better time.
- Upon collision, the game-over screen appears with your time.
- Restart the game by clicking the "Restart" button.
Further Improvements
To enhance the game further, consider implementing the following:
- Graphics: Replace the simple rectangles with images or sprites for the car and obstacles.
- Animations: Add animations for movements and collisions.
- Sound Effects: Integrate sounds for a more immersive experience.
- Multiple Levels: Introduce levels with varying difficulty, such as increasing speed or obstacle frequency.
- Power-Ups: Add collectible items that grant bonuses, like temporary invincibility or speed boosts.
- Mobile Support: Implement touch controls to make the game playable on mobile devices.
- Responsive Design: Make the canvas and UI responsive to different screen sizes.
Enjoy building and customizing your 2D Car Racing Game! This foundational structure provides a solid base upon which you can add more features and polish to create an engaging gaming experience.