Skip to main content

How To Create 3D Car Racing Game in React.js


In this tutorial, we'll create a simple car racing game using React.js. The player can move the car left and right using the keyboard arrow keys. The opponent cars will move from the top to the bottom, and the game will end with a "Game Over" alert when the player's car collides with an opponent car. The speed of the opponent cars will gradually increase, making the game more challenging.

Step 1: Set Up the Project

First, make sure you have create-react-app installed. If not, install it using the following command:

npx create-react-app car-racing-game

Navigate to your project directory:

cd car-racing-game

Step 2: Install Styled-Components

We will use styled-components for styling our components. Install it using the following command:

npm install styled-components

Step 3: Create the Game Components

Create a new file src/App.js and replace its content with the following code:


import React, { useState, useEffect } from 'react';
import styled, { keyframes } from 'styled-components';

const moveRoad = keyframes\`
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: 0 100%;
  }
\`;

const GameContainer = styled.div\`
  width: 500px;
  height: 700px;
  border: 1px solid black;
  margin: 50px auto;
  position: relative;
  overflow: hidden;
  background-color: #333;
  background-image: linear-gradient(#555 20%, transparent 20%, transparent 40%, #555 40%, #555 60%, transparent 60%, transparent 80%, #555 80%);
  background-size: 100% 50px;
  animation: \${moveRoad} 2s linear infinite;
\`;

const Car = styled.img\`
  width: 50px;
  height: 100px;
  position: absolute;
  top: \${(props) => (props.isPlayer ? 'auto' : props.y + 'px')};
  bottom: \${(props) => (props.isPlayer ? '10px' : 'auto')};
  left: \${(props) => props.x + 'px'};
  border-radius: 5px;
\`;

const Score = styled.div\`
  position: absolute;
  top: 10px;
  left: 10px;
  color: white;
  font-size: 20px;
  font-family: Arial, sans-serif;
\`;

const App = () => {
  const [playerX, setPlayerX] = useState(225); // Player car's initial x position
  const [opponents, setOpponents] = useState([]);
  const [score, setScore] = useState(0);
  const [gameOver, setGameOver] = useState(false);

  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'ArrowLeft' && playerX > 0) setPlayerX(playerX - 20);
      if (e.key === 'ArrowRight' && playerX < 450) setPlayerX(playerX + 20);
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [playerX]);

  useEffect(() => {
    const interval = setInterval(() => {
      if (gameOver) return;

      setOpponents((prevOpponents) =>
        prevOpponents
          .map((opponent) => ({ ...opponent, y: opponent.y + opponent.speed }))
          .filter((opponent) => opponent.y < 700)
      );

      setOpponents((prevOpponents) => {
        const newOpponent = {
          x: Math.random() * 450,
          y: -100,
          speed: Math.random() * 5 + 4 + score / 50, // Adjusted speed
        };
        return prevOpponents.length < 4 ? [...prevOpponents, newOpponent] : prevOpponents;
      });

      setScore((prevScore) => prevScore + 1);

      setOpponents((prevOpponents) => {
        for (let opponent of prevOpponents) {
          if (
            opponent.y + 100 >= 600 &&
            opponent.x < playerX + 50 &&
            opponent.x + 50 > playerX
          ) {
            setGameOver(true);
            alert(\`Game Over! Score: \${score}\`);
            clearInterval(interval);
          }
        }
        return prevOpponents;
      });
    }, 50); // Adjusted interval time

    return () => clearInterval(interval);
  }, [opponents, playerX, score, gameOver]);

  return (
    
      Score: {score}
      
      {opponents.map((opponent, index) => (
        
      ))}
    
  );
};

export default App;
    

Make sure to replace "path/to/player-car.png" and "path/to/opponent-car.png" with the actual paths to your car images.

Conclusion

With these steps, you have created a basic car racing game in React.js. The player can move the car left and right, and the opponent cars move from the top to the bottom. The game ends with a "Game Over" alert when the player's car collides with an opponent car, and the score is displayed on the screen.

Comments

Popular posts from this blog

Creating an Interactive Tic Tac Toe Game

In this tutorial, we'll walk through the steps to create a dynamic Tic Tac Toe game using HTML, CSS, and JavaScript. This classic game is a great way to practice your web development skills and learn more about interactive web applications. HTML Structure We'll start with the HTML structure, which includes the game board, a reset button, and a status display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tic Tac Toe</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Tic Tac Toe</h1> <div id="board" class="board"></div> <button id="reset">Reset Game</button> <div id=...

How To Make Casio Calculator using HTML, CSS Javascript with all Functional features

Creating a Casio FX-991CW calculator using HTML, CSS, and JavaScript is an engaging project for learning web development. This guide will help you create a functional calculator that can perform basic arithmetic, trigonometric functions, and square root calculations. Step 1: HTML Structure First, set up the HTML structure for the calculator. Here's an example: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Casio FX-991CW Calculator</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="calculator"> <input type="text" class="calculator-screen" id="main-screen" value="" disabled /> <input type="text" class="calculator-screen" ...

Creating a Simple Car Racing Game with HTML, CSS, Javascript

In this post, we will create a simple car racing game using HTML, CSS, and JavaScript. This game will feature a player car, an opponent car, and a score counter. The player can move their car left and right to avoid collisions with the opponent car. Let's dive into the code! HTML Structure The HTML structure consists of a game area that contains the road, player car, opponent car, and score display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car Racing Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="gameArea"> <div class="road"></div> <div class="playerCar"></div> <div class="opponentCar"></div...