# Creating a Simple 3D Endless Runner Game Using Three.js

The web platform has had a tremendous growth in recent times with the help of HTML5, WebGL, and the increased power of the current generation of devices. Now mobile devices and browsers are capable of delivering high-performing content both in 2D and 3D. The familiarity of JavaScript (JS) as a scripting language has also been a driving factor, after the demise of the Flash web platform.

Most web developers are well aware of how complicated the JS ecosystem is with all the various frameworks and standards available, which could sometimes be overwhelming to a new developer. But when it comes to 3D, the choices are straightforward, thanks to Mr.Doob. His Three.js is currently the best option out there to create high-performing 3D WebGL content. Another powerful alternative is Babylon.js, which could also be used to make 3D games.

In this tutorial, you'll learn to create a simple endless runner style native web 3D game using the powerful Three.js framework. You will use the arrow keys to control a snowball rolling down a mountainside in order to dodge the trees in your path. There is no art involved, and all visuals are created in code.

## 1. Basic 3D Scene

Envato Tuts+ already has a few tutorials which could get you started with Three.js. Here are some of them to get you started.

Let's create a basic 3D scene first, as shown here where there is a rotating cube. You can use mouse drag to orbit around the cube.

Any graphic displayed on a two-dimensional screen is practically 2D in nature, with a few important elements which provide the 3D illusion: the lighting, the shading, the shadows, and the 3D to 2D projection magic which happens via the camera. In the above scene, we enable effective lighting using these lines of code.

The renderer needs to have shadowMap enabled, the scene needs to have a light with castShadow enabled, and all 3D objects need the castShadow and receiveShadow properties set appropriately. For proper shading to happen, we should also use the MeshStandardMaterial or a more feature-rich material for our 3D objects. The camera is controlled using the nifty OrbitControls script. I would recommend playing around with the basic 3D scene by adding more primitive shapes or playing with the lighting, etc., before proceeding with the tutorial.

## 2. The Endless Runner Concept

There are many types of endless runner games, and ours is an 'endless roller'. We will create a game where a snowball is rolling down an endless mountainside where we use the arrow keys to dodge the incoming trees. One interesting thing is that this simple game will not involve any art assets, as all the components would be created by code. Here is the full game to play around.

## 3. Components of the Game

The main components or elements of the game are:

• the rolling snowball
• the random trees
• the scrolling ground
• the distance fog
• the collision effect

We will explore each of these one by one in the following section.

### The Fog

The fog is a property of the 3D scene in Three. It is always a handy trick to use in order to simulate depth or show a horizon. The colour of the fog is important for the illusion to work properly and depends on the colour of the scene and lighting. As you can see in the code below, we also set the renderer's clearColor value to be close to the colour of the fog.

In order to match the ambience, we are also using similar colour values to the lights used in the scene. Every ambient colour is a different shade of white which gels together to create the necessary effect.

### The Snowball

Our snowball is a DodecahedronGeometry three primitive shape created as shown below.

For all 3D elements in this game, we are using THREE.FlatShading to get the desired low-poly look.

### The Scrolling Mountain

The scrolling ground named rollingGroundSphere is a big SphereGeometry primitive, and we rotate it on the x axis to create the moving ground illusion. The snowball does not really roll over anything; we are just creating the illusion by keeping the ground sphere rolling while keeping the snowball stationary.

A normal sphere primitive will look very smooth and therefore won't provide the necessary ruggedness needed for the mountain slope. So we do some vertex manipulations to change the smooth sphere surface into a rugged terrain. Here is the corresponding code followed by an explanation.

We are creating a sphere primitive with 40 horizontal segments (sides) and 40 vertical segments (tiers). Each vertex of a three geometry can be accessed via the vertices array property. We loop through all the tiers between the extreme top and extreme bottom vertices to do our vertex manipulations. Each tier of the sphere geometry contains exactly sides number of vertices, which forms a closed ring around the sphere.

The first step is to rotate every odd ring of vertices to break the uniformity of the surface contours. We move every vertex in the ring by a random fraction between 0.25 and 0.75 of the distance to the next vertex. As a result of this, the vertical vertices of the sphere are not aligned in a straight line anymore, and we get a nice zigzag contour.

As the second step, we provide each vertex with a random height adjustment aligned with the normal at the vertex, irrespective of the tier to which it belongs. This results in an uneven and rugged surface. I hope the vector mathematics used here are straightforward once you consider that the centre of the sphere is considered the origin (0,0).

### The Trees

The trees appear outside our rolling track to add depth to the world, and inside as obstacles. Creating the tree is a bit more complicated than the rugged ground but follows the same logic. We use a ConeGeometry primitive to create the top green part of the tree and a CylinderGeometry to create the bottom trunk part.

For the top part, we loop through each tier of vertices and expand the ring of vertices followed by shrinking down the next ring. The following code shows the blowUpTree method used to expand the alternative ring of vertices outwards and the tightenTree method used to shrink down the next ring of vertices.

The blowUpTree method pushes out every alternative vertex in a ring of vertices while keeping the other vertices in the ring at a lesser height. This creates the pointy branches on the tree. If we use the odd vertices in one tier then we use the even vertices in the next tier so that the uniformity is broken. Once the complete tree is formed, we give it a random rotation on the y axis to make it look slightly different.

### The Explosion Effect

The block pixel explosion effect is not the most elegant one we could use, but it certainly performs well. This particular particle effect is actually a 3D geometry which is manipulated to look like an effect using the THREE.Points class.

The addExplosion method adds 20 vertices to the vertices array of the particleGeometry. The explode method is called when we need the effect to run, which randomly positions each vertex of the geometry. The doExplosionLogic gets called in the update method if the particle object is visible, where we move each vertex outwards. Each vertex in a points object gets rendered as a square block.

## 4. The Gameplay

Now that we know how to create each of the items needed for the game, let's get into the gameplay. The main gameplay elements are:

• the game loop
• the placement of the trees
• the user interaction
• the collision detection

Let's analyse those in detail.

### The Game Loop

All the core game mechanic happens in the game loop, which in our case is the update method. We call it for the first time from the init method, which gets called on window load. After this, it hooks onto the document render loop using the requestAnimationFrame method so that it gets called repeatedly.

In update, we call the render method, which uses the renderer to draw the scene. We call the doTreeLogic method, which checks for collision and also removes the trees once they have gone out of view.

The snowball and the ground spheres get rotated while we also add a random bouncing logic to the snowball. New trees are placed in the path by calling addPathTree after a pre-defined time has elapsed. Time is tracked using a THREE.Clock object. We also update the score unless a collision has occurred.

### Placement of the Trees

One set of trees is placed outside the rolling track to create the world using the addWorldTrees method. All trees are added as a child of the rollingGroundSphere so that they also move when we rotate the sphere.

To plant world trees, we call the addTree method by passing values around the circumference of our ground sphere. The sphericalHelper utility helps us find the position on the surface of a sphere.

To plant trees on the path, we will make use of a pool of trees which are created on start using the createTreesPool method. We also have pre-defined angle values for each path on the sphere stored in the pathAngleValues array.

The addPathTree method is called from update when enough time has elapsed after planting the last tree. It in turn calls the addTree method shown earlier with a different set of parameters where the tree gets placed in the selected path. The doTreeLogic method will return the tree to the pool once it goes out of view.

### User Interaction

We are adding a listener to the document to look for relevant keyboard events. The handleKeyDown method sets the currentLane value if the right or left arrow keys are pressed or sets the bounceValue value if up arrow is pressed.

In update, the x position of our snowball is slowly incremented to reach the currentLane position there by switching lanes.

### Collision Detection

There is no real physics involved in this particular game, although we could use various physics frameworks for our collision detection purpose. But as you are well aware, a physics engine adds a lot of performance overhead to our game, and we should always try to see if we can avoid it.

In our case, we just calculate the distance between our snowball and each tree to trigger a collision if they are very close. This happens in the doTreeLogic method, which gets called from update.

As you may have noticed, all trees currently present in our path are stored in the treesInPath array. The doTreeLogic method also removes the trees from display and into the pool once they go out of our view using the code shown below.

## Conclusion

Creating a 3D game is a complicated process if you are not using a visual tool like Unity. It could seem intimidating or overwhelming, but let me assure you that once you get the hang of it, you'll feel a lot more powerful and creative. I would like you to explore further using the various physics frameworks or particle systems or the official examples.