Skip to content
ImagineWorld

Adding Physics and Sounds to Your Scene

node_idnode-book_learn-three-js_chapter-12-adding-physics-and-sounds-to-your-scene
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleAdding Physics and Sounds to Your Scene
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Adding Physics and Sounds to Your Scene

Section titled “Chapter 12 — Adding Physics and Sounds to Your Scene”

In this chapter, we’ll look at Rapier, another library you can use to extend the basic functionality of Three.js. Rapier is a library that allows you to introduce physics into your 3D scene. By physics, we mean that your objects are subject to gravity – they can collide with one another, can be moved by applying impulses, and can be constrained in their movement by different types of joints. Besides physics, we’ll also look at how Three.js can help you with adding spatial sounds to your scene.

In this chapter, we’ll discuss the following topics:

  • Creating a Rapier scene where your objects are subject to gravity and can collide with one another
  • Showing how to change the friction and restitution (bounciness) of the objects in the scene
  • Explaining the various shapes supported by Rapier and how to use them
  • Showing how to create compound shapes by combining simple shapes
  • Showing how a height field allows you to simulate a complex shape
  • Limiting the movement of an object by using joints to connect them to other objects
  • Adding sound sources to your scene, whose sound volume and direction are based on the distance to the camera

Available physics engines

There are a number of different open source JavaScript physics engines available. Most of them are not under active development though. Rapier, however, is under active development. Rapier is written in Rust and is cross-compiled to JavaScript, so you can use it in the browser. Should you choose to use any of the other libraries out there, the information in this chapter will still be useful since most of the libraries use the same approach as demonstrated in this chapter. Therefore, while the implementation and classes and functions used might be different, the concepts and setup shown in this chapter will, for the most part, be applicable regardless of the physics library you choose.

Creating a basic Three.js scene with Rapier

Section titled “Creating a basic Three.js scene with Rapier”

To get started, we created a very basic scene in which a cube drops down and hits a plane. You can see this example by looking at the physics-setup.html example:

Figure 12.1 – Simple Rapier physics

When you open this example, you’ll see the cube slowly drop down, hit the corner of the gray horizontal plane, and bounce off it. We could have accomplished this without using a physics engine by updating the position and rotation of the cube and programming how it should react. This is, however, rather difficult to do since we need to know exactly when it hits, where it hits, and how the cube should spin away after the hit. With Rapier, we just have to configure the physical world, and Rapier will calculate exactly what happens to the objects in the scene.

Before we can configure our models to use the Rapier engine, we need to install Rapier in our project (we’ve already done this, so you don’t have to do this if you’re experimenting with the examples provided in this book):

$ yarn add @dimforge/rapier3d

Once added, we need to import Rapier into our project. This is done slightly differently than the normal imports we’ve seen because Rapier needs to load additional WebAssembly resources. This is needed since the Rapier library is developed in the Rust language, and compiled into WebAssembly so it can also be used on the web. To use Rapier, we need to wrap our script like this:

import * as THREE from 'three'
import { RigidBodyType } from '@dimforge/rapier3d'
// maybe other imports
import('@dimforge/rapier3d').then((RAPIER) => {
// the code
}

This last import statement will load the Rapier library asynchronously and calls the callback when all the data has been loaded and parsed. In the rest of the code, you can just call into the RAPIER object to access the Rapier-specific functionality.

To set up a scene with Rapier, we need to do a few things:

  1. Create a Rapier World. This defines the physical world that we’re simulating and allows us to define the gravity that will be applied to objects in this world.
  2. For each object you want to simulate with Rapier, you’ve got to define a RigidBodyDesc. This defines the position and rotation of an object in the scene (as well as some other properties). By adding this description to the World instance, you get back a RigidBody.
  3. Next, you can tell Rapier the shape of the object you’re adding by creating a ColliderDesc object. This will tell Rapier that your object is a cube, sphere, cone, or another shape; how large it is; how much friction it has with regard to other objects; and how bouncy it is. This description is then combined with the previously created RigidBody to create a Collider instance.
  4. In our animation loop, we can now call world.step(), which makes Rapier calculate all the new positions and rotations of the RigidBody objects that it is aware of.

Online Rapier documentation

In this book, we’ll look at various properties of Rapier. We won’t explore the full set of features provided by Rapier since that could fill a book in itself. More information on Rapier can be found here: https://rapier.rs/docs/.

Let’s walk through these steps and see how you combine this with the Three.js objects you’re already familiar with.

Setting up the world and creating the descriptions

Section titled “Setting up the world and creating the descriptions”

The first thing we need to do is create the World we’re simulating with:

const gravity = { x: 0.0, y: -9.81, z: 0.0 }
const world = new RAPIER.World(gravity)

This is straightforward code in which we create a World that has a gravity of -9.81 on the y -axis. This is similar to the gravity on Earth.

Next, let’s define the Three.js object we saw in our example: a cube that falls and the floor that it hits:

const floor = new THREE.Mesh(
new THREE.BoxGeometry(5, 0.25, 5),
new THREE.MeshStandardMaterial({color: 0xdddddd})
)
floor.position.set(2.5, 0, 2.5)
const sampleMesh = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshNormalMaterial()
)
sampleMesh.position.set(0, 4, 0)
scene.add(floor)
scene.add(sampleMesh)

Nothing new here. We just define two THREE.Mesh objects and position the sampleMesh instance, the cube, above the corner of the floor surface. Next, we need to create the RigidBodyDesc and ColliderDesc objects, which represent the THREE.Mesh objects in the world of Rapier. We’ll start with the simple one, the floor:

const floorBodyDesc = new RAPIER.RigidBodyDesc
(RigidBodyType.Fixed)
const floorBody = world.createRigidBody(floorBodyDesc)
floorBody.setTranslation({ x: 2.5, y: 0, z: 2.5 })
const floorColliderDesc = RAPIER.ColliderDesc.cuboid
(2.5, 0.125, 2.5)
world.createCollider(floorColliderDesc, floorBody)

Here, first, we create a RigidBodyDesc with a single parameter, RigidBodyType.Fixed. A fixed rigid body means that Rapier isn’t allowed to change the position or the rotation of this object, so this object won’t be affected by gravity or moved around when another object hits it. By calling world.createRigidBody, we add it to the world known by Rapier so that Rapier can take this object into account when doing its calculations. Then, we use setTranslation to put RigidBody into the same position as our Three.js floor. The setTranslation function takes an optional extra parameter called wakeUp. If RigidBody is sleeping (what can happen if it hasn’t moved for a long time), passing in true for the wakeUp property makes sure that Rapier will take RigidBody into account when determining the new positions of all the objects that it is aware of.

We still need to define the shape of this object so that Rapier can tell when it collides with another object. For this, we use the Rapier.ColliderDesc.cuboid function in which we specify the shape. For the cuboid function, Rapier expects the shape to be defined by a half-width, a half-height, and a half-depth. The final step to take is to add this collider to the world and connect it to the floor. For this, we use the world.createCollider function.

At this point, we have defined floor in the Rapier world, which corresponds to the floor in our Three.js scene. Now, we define the cube that will fall in the same way:

Const rigidBodyDesc = new RAPIER.RigidBodyDesc
(RigidBodyType.Dynamic)
.setTranslation(0, 4, 0)
const rigidBody = world.createRigidBody(rigidBodyDesc)
const rigidBodyColliderDesc = RAPIER.ColliderDesc.cuboid
(0.5, 0.5, 0.5)
const rigidBodyCollider = world.createCollider
(rigidBodyColliderDesc, rigidBody)
rigidBodyCollider.setRestitution(1)

This code fragment is similar to the previous one – we just create the relevant objects for Rapier that correspond to the objects in our Three.js scene. The main change here is that we used a RigidBodyType.Dynamic instance. This means that this object can be completely managed by Rapier. Rapier can change its position or its translation.

Additional rigid body types provided by Rapier

Besides the Dynamic and the Fixed rigid body types, Rapier also provides a KinematicPositionBased type, for managing the position of an object, or a KinematicVelocityBased type, for managing the velocity of an object ourselves. More information on this can be found here: https://rapier.rs/docs/user_guides/javascript/rigid_bodies.

Rendering the scene and simulating the world

Section titled “Rendering the scene and simulating the world”

What is left to do is render the Three.js object, simulate the world, and make sure that the positions of the objects managed by Rapier correspond to the position of the Three.js meshes:

const animate = (renderer, scene, camera) => {
// basic animation loop
requestAnimationFrame(() => animate(renderer, scene,
camera))
renderer.render(scene, camera)
world.step()
// copy over the position from Rapier to Three.js
const rigidBodyPosition = rigidBody.translation()
sampleMesh.position.set(
rigidBodyPosition.x,
rigidBodyPosition.y,
rigidBodyPosition.z)
// copy over the rotation from Rapier to Three.js
const rigidBodyRotation = rigidBody.rotation()
sampleMesh.rotation.setFromQuaternion(
new THREE.Quaternion(rigidBodyRotation.x,
rigidBodyRotation.y, rigidBodyRotation.z,
rigidBodyRotation.w)
)
}

In our render loop, we have the normal Three.js elements to make sure we render this each step using requestAnimationFrame. Besides that, we call the world.step() function to trigger a calculation in Rapier. This will update the position and rotation of all the objects that it knows of. Next, we need to make sure that these newly calculated positions are also reflected by the Three.js objects. To do this, we just get the current position of an object in the Rapier world (rigidBody.translation()) and set the position of the Three.js mesh to the result of that function. For the rotation, we do the same, by calling rotation() on rigidBody first, and then applying that rotation to our Three.js mesh. Rapier works with quaternions for defining rotations, so we need to make this conversion before we can apply that rotation to the Three.js mesh.

And that’s all you need to do. All the examples in the following sections use this same approach:

  • Setting up the Three.js scene
  • Setting up a similar set of objects in the Rapier world
  • Making sure that after each step, the location and rotation of both the Three.js scene and the Rapier world align again

In the next section, we’ll expand on this example, and we’ll show you more about how objects interact with each other when they collide in the Rapier world.

The following example is built upon the same core concepts we looked at in the Setting up the world and creating the descriptions section. The example can be viewed by opening up the dominos.html example:

Figure 12.2 – Dominos standing still when no gravity is present

Here, you can see that we’ve created a simple floor on which many dominos are positioned. If you look closely, you can see that the first instance of these dominos is tilted a little bit. If we enable gravity on the y -axis using the menu on the right, you’ll see that the first dominos falls, hits the next one, and so on until all the dominos have been knocked down:

Figure 12.3 – Dominos falling down after the first one is toppled

Creating this with Rapier is really straightforward. We just need to create the Three.js objects that represent the dominos, create the relevant Rapier RigidBody and Collider elements, and make sure the changes to the Rapier objects are reflected by the Three.js objects.

First, let’s have a quick look at how we create the Three.js dominos:

const createDominos = () => {
const getPoints = () => {
const points = []
const r = 2.8; const cX = 0; const cY = 0
let circleOffset = 0
for (let i = 0; i < 1200; i += 6 + circleOffset) {
circleOffset = 1.5 * (i / 360)
const x = (r / 1440) * (1440 - i) * Math.cos(i *
(Math.PI / 180)) + cX
const z = (r / 1440) * (1440 - i) * Math.sin(i *
(Math.PI / 180)) + cY
const y = 0
points.push(new THREE.Vector3(x, y, z))
}
return points
}
const stones = new Group()
stones.name = 'dominos'
const points = getPoints()
points.forEach((point, index) => {
const colors = [0x66ff00, 0x6600ff]
const stoneGeom = new THREE.BoxGeometry
(0.05, 0.5, 0.2)
const stone = new THREE.Mesh(
stoneGeom,
new THREE.MeshStandardMaterial({color: colors[index
% colors.length], transparent: true, opacity: 0.8})
)
stone.position.copy(point)
stone.lookAt(new THREE.Vector3(0, 0, 0))
stones.add(stone)
})
return stones
}

In this code fragment, we determine the position of the dominos with the getPoints function. This function returns a list of THREE.Vector3 objects that represent the position of the individual stones. Each stone is placed along a spiral outward from the center. Next, these points are used to create a number of THREE.BoxGeometry objects at the same locations. To make sure the dominos are oriented correctly, we use the lookAt function to have them ‘look at’ the center of the circle. All the dominos are added to a THREE.Group object, which we then add to a THREE.Scene instance (this is not shown in the code fragment).

Now that we have our set of THREE.Mesh objects, we can create the corresponding set of Rapier objects:

const rapierDomino = (mesh) => {
const stonePosition = mesh.position
const stoneRotationQuaternion = new THREE.Quaternion().
setFromEuler(mesh.rotation)
const dominoBodyDescription = new RAPIER.RigidBodyDesc
(RigidBodyType.Dynamic)
.setTranslation(stonePosition.x, stonePosition.y,
stonePosition.z)
.setRotation(stoneRotationQuaternion))
.setCanSleep(false)
.setCcdEnabled(false)
const dominoRigidBody = world.createRigidBody
(dominoBodyDescription)
const geometryParameters = mesh.geometry.parameters
const dominoColliderDesc = RAPIER.ColliderDesc.cuboid(
geometryParameters.width / 2,
geometryParameters.height / 2,
geometryParameters.depth / 2
)
const dominoCollider = world.createCollider
(dominoColliderDesc, dominoRigidBody)
mesh.userData.rigidBody = dominoRigidBody
mesh.userData.collider = dominoCollider
}

This code will look familiar to the code in Setting up the world and creating the descriptions section. Here, we take the position and rotation of the passed-in THREE.Mesh instance and use that information to create the relevant Rapier objects. To make sure we can access the dominoCollider and dominoRigidBody instances in the render loop, we add them to the userData property of the passed-in mesh.

The final step here is to update the THREE.Mesh objects in the render loop:

const animate = (renderer, scene, camera) => {
requestAnimationFrame(() => animate(renderer, scene,
camera))
renderer.render(scene, camera)
world.step()
const dominosGroup = scene.getObjectByName('dominos')
dominosGroup.children.forEach((domino) => {
const dominoRigidBody = domino.userData.rigidBody
const position = dominoRigidBody.translation()
const rotation = dominoRigidBody.rotation()
domino.position.set(position.x, position.y,
position.z)
domino.rotation.setFromQuaternion(new
THREE.Quaternion(rotation.x, rotation.y,
rotation.z, rotation.w))
})
}

In each loop, we tell Rapier to calculate the next state of the world (world.step), and for each domino (which are children of the THREE.Group named dominos), we update the position and rotation of the THREE.Mesh instance based on the RigidBody object stored in that mesh’s userdata information.

Before we move on to the most important properties provided by a collider, we’ll have a quick look at how gravity affects this scene. When you open this example, with the help of the menu on the right, you can change the gravity of the world. You can use this to experiment with how the dominos respond to different gravity settings. For instance, the following example shows the situation where, after all the dominos have fallen, we increased the gravity along the x -axis and z -axis:

Figure 12.4 – Dominos with different gravity settings

In the next section, we’ll show the effect that setting the friction and restitution has on the Rapier objects.

In the next example, we’ll look a bit closer at the restitution and friction properties of the Collider provided by Rapier.

restitution is the property that defines how much energy an object keeps after it collides with another object. You can look at it a bit like bounciness. A tennis ball has high restitution, while a brick has low restitution.

friction defines how easily an object glides on top of another object. Objects with high friction slow down quickly when moving on top of another object, while objects with low friction can easily glide. Something such as ice has low friction, while sandpaper has high friction.

We can set these properties during the construction of the RAPIER.ColliderDesc object or set it afterward when we’ve already created the collider using the (world.createCollider(...) function. Before we look at the code, we’ll have a look at the example. For the colliders-properties.html example, you’ll see a big box into which you can drop shapes:

Figure 12.5 – Empty box to drop shapes into

With the menu on the right, you can drop in sphere and cube shapes, and set the friction and restitution for the added objects. For the first scenario, we’ll add a large number of cubes with high friction.

Figure 12.6 – Box with cubes with high friction

What you see here is that even though the box is moving around its axis, the cubes barely move around. This is because the cubes themselves have very high friction. If you try this with low friction, you’ll see that the boxes will slide around in the bottom of the box.

To set the friction, all you have to do is this:

const rigidBodyDesc = new RAPIER.RigidBodyDesc
(RigidBodyType.Dynamic)
const rigidBody = world.createRigidBody(rigidBodyDesc)
const rigidBodyColliderDesc = RAPIER.ColliderDesc.ball(0.2)
const rigidBodyCollider = world.createCollider
(rigidBodyColliderDesc, rigidBody)
rigidBodyCollider.setFriction(0.5)

Rapier provides one more way of controlling friction and that is by setting the combine rule using the setFrictionCombineRule function. This tells Rapier how to combine the friction of the two objects that have collided (in our example, the bottom of the box and the cube). With Rapier, you can set this to the following values:

  • CoefficientCombineRule.Average: The average of the two coefficients is used
  • CoefficientCombineRule.Min: The minimum among the two coefficients is used
  • CoefficientCombineRule.Multiply: The product of the two coefficients is used
  • CoefficientCombineRule.Max: The maximum among the two coefficients is used

To explore how restitution works, we can use this same example (colliders-properties.html):

Figure 12.7 – Box with spheres with high restitution

Here, we’ve increased the restitution of the spheres. The result is that they now bounce around in the box when added or when they hit a wall. To set the restitution, you use the same approach as for the friction:

const rigidBodyDesc = new RAPIER.RigidBodyDesc
(RigidBodyType.Dynamic)
const rigidBody = world.createRigidBody(rigidBodyDesc)
const rigidBodyColliderDesc = RAPIER.ColliderDesc.ball(0.2)
const rigidBodyCollider = world.createCollider
(rigidBodyColliderDesc, rigidBody)
rigidBodyCollider.setRestitution(0.9)

Rapier also allows you to set how the restitution property of the objects that hit each other is calculated. You can use the same values but this time, you use the setRestitutionCombineRule function.

The Collider has additional properties you can use to fine-tune how the collider interacts with the Rapier view of the world, and what happens when objects collide. Rapier itself provides very good documentation for this. Specifically for the colliders, you can find that documentation here: https://rapier.rs/docs/user_guides/javascript/colliders#restitution.

Rapier provides a number of shapes you can use to wrap your geometries. In this section, we’ll walk you through all the available Rapier shapes and demonstrate these meshes through an example. Note that to use these shapes you need to call RAPIER.ColliderDesc.roundCuboid, RAPIER.ColliderDesc.ball, and so on.

Rapier provides 3D shapes and 2D shapes. We’ll only look at the 3D shapes provided by Rapier:

  • ball: A ball shape, configured by setting the radius of the ball
  • capsule: A capsule shape, defined by the half-height of the capsule and its radius
  • cuboid: A simple cube shape defined by passing in the half-width, half-height, and half-depth of the shape
  • heightfield: A height field is a shape for which each provided value defines the height of a 3D plane
  • cylinder: A cylinder shape defined by the half-height and the radius of the cylinder
  • cone: A cone shape defined by the half-height and the radius of the bottom of the cylinder
  • convexHull: A convex hull is the smallest shape that encompasses all the passed-in points
  • convexMesh: A convex mesh also takes a number of points, but it is assumed that these points already form a convex hull, so Rapier won’t make any calculations to determine the smaller shape

Besides these shapes, Rapier also provides an additional rounded variant for a few of these shapes: roundCuboid, roundCylinder, roundCone, roundConvexHull, and roundConvexMesh.

We’ve provided another example in which you can what these shapes look like and how they interact when they collide with each other. Open up the shapes.html example to see this in action:

Figure 12.8 – Shapes on top of a heightfield object

When you open this example, you’ll see an empty heightfield object. With the menu on the right, you can add different shapes and they’ll collide with each other and with the heightfield instance. Once again, you can set the specific restitution and friction values for the objects you’re adding. Since we’ve already explained in the previous sections how to add the shape in Rapier and make sure the corresponding shapes in Three.js are updated, we won’t go into detail here on how to create the shapes from the previous list. For the code, look at the shapes.js file in the sources for this chapter.

One final note before we move on to the section on joints – when we want to depict simple shapes (for example, balls or cubes), the way that Rapier defines this model and the way Three.js defines it are pretty much the same. Therefore, when this kind of object collides with another object, it will look correct. When we have more complex shapes, as, in this example, with a heightmap instance, there can be slight differences in how Three.js interprets and interpolates these points to a heightmap instance, and how Rapier does so. You can see this for yourself by looking at the shapes.html example, adding a lot of different shapes, and then looking at the underside of the heightfield:

Figure 12.9 – Bottom of the heightfield

What you can see here is that we can see small parts of the different objects poking through the heightmap. The reason is that Rapier has a different way of determining the exact shape of the heightmap than Three.js. In other words, Rapier thinks that the heightmap looks slightly different than Three.js does. Therefore, when it determines where specific shapes are when they collide, it can result in small details such as this. However, by tuning the sizes or creating simpler objects, this can easily be circumvented.

So far, we’ve looked at gravity and collisions. Rapier also provides a way to limit the movement and rotation of rigid bodies. We’ll explain how Rapier does this by using joints.

Using joints to limit the movement of objects

Section titled “Using joints to limit the movement of objects”

Up until now, we’ve seen some basic physics in action. We’ve seen how various shapes respond to gravity, friction, and restitution, and how this affects collision. Rapier also provides advanced constructs that allow you to limit the movement of your objects. In Rapier, these objects are called joints. The following list gives an overview of the joints that are available in Rapier:

  • Fixed joint: A fixed joint makes sure that two bodies don’t move relative to one another. This means that the distance and rotation between these two objects will always be the same.
  • Spherical joint: A spherical joint makes sure that the distance between two bodies stays the same. The bodies, however, can move around one another on all three axes.
  • Revolute joint: With this joint, the distance between the two bodies stays the same, and they are allowed to rotate on a single axis – for instance, a steering wheel, which can only rotate around a single axis.
  • Prismatic joint: Similar to the revolute joint but this time, the rotations between the objects are fixed, and the objects can move on a single axis. This causes a sliding effect – for example, such as a lift moving upward.

In the following sections, we’ll explore these joints and see them in action in the examples.

The simplest of joints is a fixed joint. With this joint, you can connect two objects, and they’ll stay at the same distance and orientation that is specified when this joint is created.

This is shown in the fixed-joint.html example:

Figure 12.10 – A fixed joint connecting two joints

As you can see in this example, the two cubes move as one. This happens because they are connected by a fixed joint. To set this up, we first have to create the two RigidBody objects and the two Collider objects, as we’ve already seen in the previous sections. The next thing we need to do is connect these two objects. For this, we first need to define JointData:

let params = RAPIER.JointData.fixed(
{ x: 0.0, y: 0.0, z: 0.0 },
{ w: 1.0, x: 0.0, y: 0.0, z: 0.0 },
{ x: 2.0, y: 0.0, z: 0.0 },
{ w: 1.0, x: 0.0, y: 0.0, z: 0.0 }
)

This means that we connect the first object at the position of { x: 0.0, y: 0.0, z: 0.0 } (its center) to the second object, which is positioned at { x: 2.0, y: 0.0, z: 0.0 }, where the first object is rotated with a quaternion of { w: 1.0, x: 0.0, y: 0.0, z: 0.0 } and the second object is rotated the same amount – { w: 1.0, x: 0.0, y: 0.0, z: 0.0 }. The only thing that we need to do now is tell the Rapier world about this joint and which RigidBody objects it applies to:

world.createImpulseJoint(params, rigidBody1, rigidBody2,
true)

The last property here defines whether the RigidBody should wake up because of this joint. A RigidBody can be put to sleep when it hasn’t moved for a couple of seconds. For joints, it is usually best to just set this to true since this makes sure that if one of the RigidBody objects to which we attach the joint is sleeping, RigidBody will wake up.

Another great way of seeing this joint in action is by using the following parameters:

let params = RAPIER.JointData.fixed(
{ x: 0.0, y: 0.0, z: 0.0 },
{ w: 1.0, x: 0.0, y: 0.0, z: 0.0 },
{ x: 2.0, y: 2.0, z: 2.0 },
{ w: 0.3, x: 1, y: 1, z: 1 }
)

This will cause the two cubes to get caught on the floor in the center of the scene:

Figure 12.11 – A fixed joint connecting two cubes

Next on our list is the spherical joint.

A spherical joint allows two objects to freely move around one another while keeping the same distance between these objects. This can be used for ragdoll effects or, as we did in this example, creating a chain (sphere-joint.html):

Figure 12.12 – Multiple spheres connected by a spherical joint

As you can see in this example, we’ve connected a large number of spheres to create a chain of spheres. When these spheres hit the cylinder in the middle, they’ll wrap around and slowly glide off this cylinder. You can see that while the orientation between these spheres changes based on their collisions, the absolute distance between the spheres stays the same. So, to set up this example, we’ve created a number of spheres with RigidBody and Collider, similar to the previous examples. For each set of two spheres, we also create a joint like this:

const createChain = (beads) => {
for (let i = 1; i < beads.length; i++) {
const previousBead = beads[i - 1].userData.rigidBody
const thisBead = beads[i].userData.rigidBody
const positionPrevious = beads[i - 1].position
const positionNext = beads[i].position
const xOffset = Math.abs(positionNext.x –
positionPrevious.x)
const params = RAPIER.JointData.spherical(
{ x: 0, y: 0, z: 0 },
{ x: xOffset, y: 0, z: 0 }
)
world.createImpulseJoint(params, thisBead,
previousBead, true)
}
}

You can see that we create a joint using RAPIER.JointData.spherical. The parameters here define the position of the first object, { x: 0, y: 0, z: 0 }, and the relative position of the second object, { x: xOffset, y: 0, z: 0 }. We do this for all the objects and add the joints to the rapier world using world.createImpulseJoint(params, thisBead, ``previousBead, true).

The result is that we’ve got a chain of spheres that is connected using these spherical joints.

The next joint, the revolute joint, allows us to restrict the movement of two objects by specifying a single axis around which an object is allowed to rotate in relation to another object.

With a revolute joint, it is easy to create gear, wheel, and fan-like constructs that rotate around a single axis. The easiest way to explain this is by looking at the revolute-joint.html example:

Figure 12.13 – A cube before it is dropped on a rotating bar

In Figure 12*.13*, you can see a purple cube hovering above a green bar. When you enable gravity in the y direction, the cube will drop on top of the green bar. The center of this green bar is connected to the fixed cube in the middle using a revolute joint. The result is that this green bar will now slowly rotate because of the weight of the purple cube:

Figure 12.14 – The bar responding to the weight on one end

For a revolute joint to work, we once again need two rigid bodies. The Rapier part of the gray cube is defined like this:

const bodyDesc = new RAPIER.RigidBodyDesc(RigidBodyType.Fixed)
const body = world.createRigidBody(bodyDesc)
const colliderDesc = RAPIER.ColliderDesc.cuboid(0.5, 0.5, 0.5)
const collider = world.createCollider(colliderDesc, body)

This means, that this RigidBody will always be in the same location regardless of any forces exerted on it. The green bar is defined like this:

Const bodyDesc = new RAPIER.RigidBodyDesc
(RigidBodyType.Dynamic)
.setCanSleep(false)
.setTranslation(-1, 0, 0)
.setAngularDamping(0.1)
const body = world.createRigidBody(bodyDesc)
const colliderDesc = RAPIER.ColliderDesc.cuboid(0.25, 0.05,
2)
const collider = world.createCollider(colliderDesc, body)

Nothing special here, but we have introduced a new property could angularDamping. With angular damping, Rapier will slowly decrease the rotation speed of a RigidBody. In our example, this means that the bar will slowly stop rotating after a while.

And the box that we’re dropping looks like this:

Const bodyDesc = new RAPIER.RigidBodyDesc
(RigidBodyType.Dynamic)
.setCanSleep(false)
.setTranslation(-1, 1, 1)
const body = world.createRigidBody(bodyDesc)
const colliderDesc = RAPIER.ColliderDesc.cuboid
(0.1, 0.1, 0.1)
const collider = world.createCollider(colliderDesc, body)

So, at this point, we have defined RigidBody. Now, we can connect the fixed box with the green bar:

const params = RAPIER.JointData.revolute(
{ x: 0.0, y: 0, z: 0 },
{ x: 1.0, y: 0, z: 0 },
{ x: 1, y: 0, z: 0 }
)
let joint = world.createImpulseJoint(params, fixedCubeBody,
greenBarBody, true)

The first two parameters determine the position at which the two rigid bodies are connected (following the same idea as with the fixed joint). The last parameter defines the vector at which the bodies can rotate in relation to one another. Since our first RigidBody is fixed, only the green bar can rotate.

The last joint type supported by Rapier is the prismatic joint.

Limiting movement to a single axis with a prismatic joint

Section titled “Limiting movement to a single axis with a prismatic joint”

The prismatic joint limits the movement of an object to a single axis. This is demonstrated in the following example (prismatic.html), where the movement of the reddish cube is limited to a single axis:

Figure 12.15 – Red cube is limited to one axis

In this example, we throw a cube at the green bar with the revolute joint from the previous example. This will cause the green bar to spin around its y -axis at the center and hit the reddish cube. This cube is limited to movement along a single axis, and you’ll see it moving along that axis.

To create the joint for this example, we used the following piece of code:

const prismaticParams = RAPIER.JointData.prismatic(
{ x: 0.0, y: 0.0, z: 0 },
{ x: 0.0, y: 0.0, z: 3 },
{ x: 1, y: 0, z: 0 }
)
prismaticParams.limits = [-2, 2]
prismaticParams.limitsEnabled = true
world.createImpulseJoint(prismaticParams, fixedCubeBody,
redCubeBody, true)

We once again define the position ({ x: 0.0, y: 0.0, z: 0 }) of fixedCubeBody first, which defines the object we’re moving in relation to. Then, we define the position of our cube – { x: 0.0, y: 0.0, z: 3 }. Finally, we define the axis along which our object is allowed to move. In this case, we defined { x: 1, y: 0, z: 0 }, which means it is allowed to move along its x -axis.

Using joint motors to move objects around their allowed axis

Spherical, revolute, and prismatic joints also support something called motors. With motors, you can move a rigid body along its allowed axis. We haven’t shown this in these examples but by using motors, you can add gears that move around automatically or create a car where you move the wheels using revolute joints with the help of a motor. For more information on motors, see the relevant section of the Rapier documentation here: https://rapier.rs/docs/user_guides/javascript/joints#joint-motors.

As we mentioned in the Creating a basic Three.js scene with Rapier section, we’ve only scratched the surface of what is possible with Rapier. Rapier is an extensive library with many features that allow fine-tuning and should provide support for most cases in which you might need a physics engine. The library is actively being developed, and the online documentation is very good.

With the examples in this chapter and the online documentation, you should be able to integrate Rapier into your own scenes even for the features not explained in this chapter.

We’ve mainly looked at 3D models and how to render them in Three.js. However, Three.js also provides support for 3D sounds. In the next section, we’ll show you an example of how you can add directional sound to a Three.js scene.

Having discussed several relevant topics by now, we have a lot of the ingredients in place to create beautiful scenes, games, and other 3D visualizations. What we haven’t shown, however, is how to add sounds to your Three.js scene. In this section, we’ll look at two Three.js objects that allow you to add sources of sound to your scene. This is especially interesting since these sound sources respond to the position of the camera:

  • The distance between the sound source and the camera determines the volume of the sound source
  • The positions of the left-hand side and the right-hand side of the camera determine the sound volume of the left-hand side speaker and the right-hand side speaker, respectively

The best way to explain this is to see this in action. Open up the audio.html example in your browser, and you’ll see a scene from Chapter 9, Animations and Moving the Camera:

Figure 12.16 – A scene with audio elements

This example uses the first-person controls we saw in Chapter 9, so you can use the arrow keys in combination with the mouse to move around the scene. Since browsers don’t support starting audio automatically anymore, first, hit the enableSounds button in the menu on the right to turn on the sounds. When you do this, you’ll hear water coming from somewhere nearby – and you’ll be able to hear some cows and some sheep in the distance.

The water sounds come from the water wheel behind your starting position, the sounds from the sheep come from the flock of sheep to the right, and the cow sounds are centered on the two oxen pulling the plow. If you use the controls to move around the scene, you’ll notice that the sounds change based on where you are – the nearer you get to the sheep, the better you’ll hear them, and as you move to the left, the sounds of the oxen will be louder. This is something called positional audio, where the volume and direction are used to determine how to play the sounds.

Accomplishing this only takes a small amount of code. The first thing we need to do is define a THREE.AudioListener object and add it to THREE.PerspectiveCamera:

const listener = new THREE.AudioListener(); camera.add(listener1);

Next, we need to create a THREE.Mesh (or a THREE.Object3D) instance and add a THREE.PositionalAudio object to that mesh. This will determine the source location of this specific sound:

const mesh1 = new THREE.Mesh(new THREE.BoxGeometry(1, 1,
1), new THREE.MeshNormalMaterial({ visible: false }))
mesh1.position.set(-4, -2, 10)
scene.add(mesh1)
const posSound1 = new THREE.PositionalAudio(listener)
const audioLoader = new THREE.AudioLoader()
audioLoader.load('/assets/sounds/water.mp3', function
(buffer) {
posSound1.setBuffer(buffer)
posSound1.setRefDistance(1)
posSound1.setRolloffFactor(3)
posSound1.setLoop(true)
mesh1.add(posSound3)

As you can see from this code snippet, we first create a standard THREE.Mesh instance. Next, we create a THREE.PositionalAudio object, which we connect to the THREE.AudioListener object that we created earlier. Finally, we add the audio and configure some properties, which define how the sound is played and how it behaves:

  • setRefDistance: This determines the distance from the object at which the sound will be reduced in volume.
  • setLoop: By default, a sound is played once. By setting this property to true, the sound loops.
  • setRolloffFactor: This determines how quickly the volume decreases as you move away from the sound source.

Internally, Three.js uses the Web Audio API (http://webaudio.github.io/web-audio-api/) to play the sound and determine the correct volume. Not all browsers support this specification. The best support currently is from Chrome and Firefox.

In this chapter, we explored how you can extend the basic 3D functionality of Three.js by adding physics. For this, we used the Rapier library, which allows you to add gravity to your scene and objects, have objects interact with each other and bounce when they collide, and use joints to limit the movement of objects relative to each other.

Besides that, we also showed you how Three.js supports 3D sounds. We created a scene where you added positional sound using the THREE.PositionalAudio and THREE.AudioListener objects.

Even though we’ve now covered all of the core functionalities provided by Three.js, there are two more chapters dedicated to exploring some external tools and libraries that you can use together with Three.js. In the next chapter, we’ll dive into Blender and see how we can use Blender’s functionality, such as baking shadows, editing UV maps, and exchanging models between Blender and Three.js.