Building Your First Browser Game with Three.js and React: Part 1 - Getting Started
Tags: threejs, react, beginners, webdev
Published: 2024-05-08 22:01:33

## Introduction

Are you ready to jump into the exciting world of **3D web games**?
In this series, we're going to build from scratch an interactive browser-based basketball game using **Three.js** and **React Three Fiber**.
Imagine controlling a basketball with simple button clicks, aiming to score as many baskets as possible. If that sounds intriguing, you’re in for a treat!

By the end of this series, not only will you have a fully functional game, but you'll also have gained a good understanding of creating 3D experiences using Three.js and React.
Check out the [final version of the game](https://mini-basket.rherault.dev/) to see what you'll be capable of creating.
It's simple, fun, and a great way to dive into the possibilities of web-based game development.

Today, we kick off with the basics—setting up our project environment using **Vite**, which provides a fast and modern way to set up a React project.

## Step 1: Setting Up Your Environment

First things first, you'll need to ensure you have Node.js installed on your computer.
Node.js will help us manage our project's dependencies and run our development server.
You can download and install Node.js from [here](https://nodejs.org/).

Once Node.js is ready, we're going to set up our project using Vite. Open your terminal and run the following commands:

```bash
# Create a new directory for your project and navigate into it
mkdir basketball-game
cd basketball-game

# Initialize a new project using Vite with a React template
npm create vite@latest . -- --template react
```

This command sets up a new React project using Vite, which includes all the boilerplate code you need to get started.

## Step 2: Installing Dependencies

Our game will utilize Three.js and React Three Fiber. We need to add these to our project.
While we're at it, we'll also install **drei**, a handy collection of abstractions for React Three Fiber that makes working with Three.js even easier.

Run the following command in your terminal:

```bash
npm install three @react-three/fiber @react-three/drei
```

These libraries are crucial as they allow us to work with 3D objects and harness React's powerful component-based architecture to manage them effectively.

## Step 3: Verify Your Project Setup

After installing your dependencies, it’s a good idea to ensure that everything is working as expected. Start your development server by running:

```bash
npm run dev
```

This command will launch your application in a local development server.
Open your browser and navigate to `http://localhost:5173` to see your new React application running. You should see a basic React welcome screen.

## Step 4: Creating a Basic 3D Scene with a Cube

Now that we have our project environment ready and our libraries installed,
let's dive into the fun part—creating our first 3D scene using Three.js and React Three Fiber.
In this step, we'll set up a simple scene with a basic cube and a camera to get a feel for how Three.js integrates within a React application.

### Setting Up the Experience Component

Inside your `src/` directory, create a new file named `Experience.jsx`.
This component will house our 3D scene. Add the following code to initialize a basic scene with a cube:

```jsx
import React from 'react';
import { Box, OrbitControls } from '@react-three/drei';

const Experience = () => {
  return (
    <>
      <ambientLight intensity={0.5} />
      <pointLight position={[10, 10, 10]} />
      <OrbitControls makeDefault />

      <Box>
        <meshStandardMaterial attach="material" color="orange" />
      </Box>
    </>
  );
}

export default Experience;
```

In this component:

- `<ambientLight>` and `<pointLight>` add basic lighting to the scene, which helps in viewing the cube.
- `<OrbitControls>` a basic control to rotate/move around the scene.
- `<Box>` is a component from `drei` that represents a 3D cube. We color it orange.

### Incorporating the Experience into Our App

Next, we need to ensure that our scene is rendered by the main application.
Delete the existing `App.js` file in the `src` folder and update the `main.jsx` file to include our `Experience` component:

```jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { Canvas } from '@react-three/fiber'
import Experience from './Experience'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Canvas>
        <Experience />
    </Canvas>
  </React.StrictMode>
)
```

This setup integrates the `Experience` component into our main application layout and adding a base `Canvas` component,
which creates a canvas element where our 3D scene will render.

### Create the base style for the 3D Experience

Now, we just need to update the existing `index.css` file to add the base of styling of our app:

```css
* {
    box-sizing: border-box;
}

html,
body {
    background-color: #ddc28d;
}

html,
body,
#root,
#main {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    user-select: none;
}
```

You can now delete the `App.jsx` file and the `App.css` file also, we don’t need them.

### Testing Your Scene

Once you have made these changes, save your files and ensure your development server is still running. Refresh your browser page at `http://localhost:5173`.
You should now see a cube rendered on the screen. You can rotate around, zooming in/out and move pressing CTRL.

If it's not appearing, make sure your development server is running correctly and that there are no errors in your console.

If you encounter any issues or have questions, don't hesitate to reach out for help.
You can contact me in comments. I'm here to assist and ensure you have a great experience building this game!

## Conclusion

Congratulations! You've just created your first 3D scene using Three.js and React Three Fiber.
This basic setup is the stepping stone to more complex and interactive 3D graphics that we will explore in upcoming posts in this series.

In the next part of our series, we will add the base models.

Stay tuned as we continue to build out our basketball game! 🏀