This course was updated in 2024. For the newer content, please visit Physics with Rapier
Video Lecture
Description
Animation can also be achieved using a Physics library. We can use a library called Cannon.js. But, rather than using the original Cannon.js, which is no longer maintained, we can install a newer fork of it named Cannon-es instead.
The Cannon physics library is ideal for simulating rigid bodies. You don't have to use it with Three.js, but it was originally built to be used with Three.js, so it will be quite easy to begin using in your project.
We will use it to make objects move and interact in a more realistic way and provide collision detection possibilities.
Shape : A geometrical shape, such as a sphere, cube or plane, used for the the physics calculations.
Rigid Body : A rigid body has a shape and a number of other properties used in the calculations such as mass and inertia.
Constraint : A 3D body has 6 degrees of freedom, 3 for position and three to describe the rotation vector. A constraint is a limit on one of the degrees of freedom.
Contact constraint : A type of constraint to simulate friction and restitution. These are like the faces of an object where the constraint is applied.
World : A collection of bodies and constraints that interact together.
Solver : The algorithm that is passed over the bodies and constraints to calculate there physical properties and adjust them accordingly.
Collision Detection
Collision detection algorithms determine what pairs of objects may be colliding. Collision detection is a computationally expensive process, so various methods can be used to simplify the collision detection.
Narrowphase : Outright body vs body collision detection. This is the most computationally expensive.
Broadphase : Is a compromise on Narrowphase where various other techniques can be used to improve collision detection performance.
Cannon provides several options for broadphase detection.
Phase
Description
NaiveBroadphase
Default. The NaiveBroadphase looks at all possible pairs without restriction, therefore it has complexity N^2. It is similar to the Narrowphase technique, except it decides first whether objects are close enough before checking if there bodies touch. NaiveBroadphase is the default and is suitable for the most common use cases, but becomes less performant if there are many objects in the physics world.
SAPBroadphase
The Sweep and Prune algorithm sorts bodies along an axis and then moves down that list finding pairs by looking at body size and position of the next bodies. For best performance, choose an axis that the bodies are spread out more on. Set 0 for X axis, 1 for Y axis and 2 for Z axis. Default axisIndex is 0 (X axis). ; E.g., // TypeScript world.broadphase = new CANNON.SAPBroadphase(world) ;(world.broadphase as CANNON.SAPBroadphase).axisIndex = 2
GridBroadphase
Axis aligned uniform grid broadphase. Divides space into a grid of cells. Bodies are placed into the cells they overlap and bodies in the same cell are paired. GridBroadphase needs to know the size of the space ahead of time. Set number of cells when you create the object. Default number of cells is X = 10, Y = 10, Z = 10.
Iterations
The Solver algorithms decide what force to add to bodies in contact. The solver is iterative, which means that it solves the equations incrementally on each animation pass. It will get closer to the solution for each iteration during the loop. A number too low for the solver iterations will result in increasingly inaccurate contact forces, which can appear as jittering or vibrations on the object, and a higher number will increase precision and stability, but also compromise performance.
import*asTHREEfrom'three'import{OrbitControls}from'three/examples/jsm/controls/OrbitControls'importStatsfrom'three/examples/jsm/libs/stats.module'import{GUI}from'dat.gui'import*asCANNONfrom'cannon-es'constscene=newTHREE.Scene()scene.add(newTHREE.AxesHelper(5))constlight1=newTHREE.SpotLight(0xffffff,100)light1.position.set(2.5,5,5)light1.angle=Math.PI/4light1.penumbra=0.5light1.castShadow=truelight1.shadow.mapSize.width=1024light1.shadow.mapSize.height=1024light1.shadow.camera.near=0.5light1.shadow.camera.far=20scene.add(light1)constlight2=newTHREE.SpotLight(0xffffff,100)light2.position.set(-2.5,5,5)light2.angle=Math.PI/4light2.penumbra=0.5light2.castShadow=truelight2.shadow.mapSize.width=1024light2.shadow.mapSize.height=1024light2.shadow.camera.near=0.5light2.shadow.camera.far=20scene.add(light2)constcamera=newTHREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)camera.position.set(0,2,4)constrenderer=newTHREE.WebGLRenderer()renderer.setSize(window.innerWidth,window.innerHeight)renderer.shadowMap.enabled=truedocument.body.appendChild(renderer.domElement)constcontrols=newOrbitControls(camera,renderer.domElement)controls.enableDamping=truecontrols.target.y=0.5constworld=newCANNON.World()world.gravity.set(0,-9.82,0)// world.broadphase = new CANNON.NaiveBroadphase()// ;(world.solver as CANNON.GSSolver).iterations = 10// world.allowSleep = trueconstnormalMaterial=newTHREE.MeshNormalMaterial()constphongMaterial=newTHREE.MeshPhongMaterial()constcubeGeometry=newTHREE.BoxGeometry(1,1,1)constcubeMesh=newTHREE.Mesh(cubeGeometry,normalMaterial)cubeMesh.position.x=-3cubeMesh.position.y=3cubeMesh.castShadow=truescene.add(cubeMesh)constcubeShape=newCANNON.Box(newCANNON.Vec3(0.5,0.5,0.5))constcubeBody=newCANNON.Body({mass:1})cubeBody.addShape(cubeShape)cubeBody.position.x=cubeMesh.position.xcubeBody.position.y=cubeMesh.position.ycubeBody.position.z=cubeMesh.position.zworld.addBody(cubeBody)constsphereGeometry=newTHREE.SphereGeometry()constsphereMesh=newTHREE.Mesh(sphereGeometry,normalMaterial)sphereMesh.position.x=-1sphereMesh.position.y=3sphereMesh.castShadow=truescene.add(sphereMesh)constsphereShape=newCANNON.Sphere(1)constsphereBody=newCANNON.Body({mass:1})sphereBody.addShape(sphereShape)sphereBody.position.x=sphereMesh.position.xsphereBody.position.y=sphereMesh.position.ysphereBody.position.z=sphereMesh.position.zworld.addBody(sphereBody)consticosahedronGeometry=newTHREE.IcosahedronGeometry(1,0)consticosahedronMesh=newTHREE.Mesh(icosahedronGeometry,normalMaterial)icosahedronMesh.position.x=1icosahedronMesh.position.y=3icosahedronMesh.castShadow=truescene.add(icosahedronMesh)constposition=(icosahedronMesh.geometry.attributes.positionasTHREE.BufferAttribute).arrayconsticosahedronPoints:CANNON.Vec3[]=[]for(leti=0;i<position.length;i+=3){icosahedronPoints.push(newCANNON.Vec3(position[i],position[i+1],position[i+2]))}consticosahedronFaces:number[][]=[]for(leti=0;i<position.length/3;i+=3){icosahedronFaces.push([i,i+1,i+2])}consticosahedronShape=newCANNON.ConvexPolyhedron({vertices:icosahedronPoints,faces:icosahedronFaces,})consticosahedronBody=newCANNON.Body({mass:1})icosahedronBody.addShape(icosahedronShape)icosahedronBody.position.x=icosahedronMesh.position.xicosahedronBody.position.y=icosahedronMesh.position.yicosahedronBody.position.z=icosahedronMesh.position.zworld.addBody(icosahedronBody)consttorusKnotGeometry=newTHREE.TorusKnotGeometry()consttorusKnotMesh=newTHREE.Mesh(torusKnotGeometry,normalMaterial)torusKnotMesh.position.x=4torusKnotMesh.position.y=3torusKnotMesh.castShadow=truescene.add(torusKnotMesh)// position = (torusKnotMesh.geometry.attributes.position as THREE.BufferAttribute).array// const torusKnotPoints: CANNON.Vec3[] = []// for (let i = 0; i < position.length; i += 3) {// torusKnotPoints.push(new CANNON.Vec3(position[i], position[i + 1], position[i + 2]));// }// const torusKnotFaces: number[][] = []// for (let i = 0; i < position.length / 3; i += 3) {// torusKnotFaces.push([i, i + 1, i + 2])// }// const torusKnotShape = new CANNON.ConvexPolyhedron(torusKnotPoints, torusKnotFaces)consttorusKnotShape=CreateTrimesh(torusKnotMesh.geometry)consttorusKnotBody=newCANNON.Body({mass:1})torusKnotBody.addShape(torusKnotShape)torusKnotBody.position.x=torusKnotMesh.position.xtorusKnotBody.position.y=torusKnotMesh.position.ytorusKnotBody.position.z=torusKnotMesh.position.zworld.addBody(torusKnotBody)functionCreateTrimesh(geometry:THREE.BufferGeometry){constvertices=(geometry.attributes.positionasTHREE.BufferAttribute).arrayconstindices=Object.keys(vertices).map(Number)returnnewCANNON.Trimesh(verticesasunknownasnumber[],indices)}constplaneGeometry=newTHREE.PlaneGeometry(25,25)constplaneMesh=newTHREE.Mesh(planeGeometry,phongMaterial)planeMesh.rotateX(-Math.PI/2)planeMesh.receiveShadow=truescene.add(planeMesh)constplaneShape=newCANNON.Plane()constplaneBody=newCANNON.Body({mass:0})planeBody.addShape(planeShape)planeBody.quaternion.setFromAxisAngle(newCANNON.Vec3(1,0,0),-Math.PI/2)world.addBody(planeBody)window.addEventListener('resize',onWindowResize,false)functiononWindowResize(){camera.aspect=window.innerWidth/window.innerHeightcamera.updateProjectionMatrix()renderer.setSize(window.innerWidth,window.innerHeight)render()}conststats=newStats()document.body.appendChild(stats.dom)constgui=newGUI()constphysicsFolder=gui.addFolder('Physics')physicsFolder.add(world.gravity,'x',-10.0,10.0,0.1)physicsFolder.add(world.gravity,'y',-10.0,10.0,0.1)physicsFolder.add(world.gravity,'z',-10.0,10.0,0.1)physicsFolder.open()constclock=newTHREE.Clock()letdeltafunctionanimate(){requestAnimationFrame(animate)controls.update()//delta = clock.getDelta()delta=Math.min(clock.getDelta(),0.1)world.step(delta)// Copy coordinates from Cannon to Three.jscubeMesh.position.set(cubeBody.position.x,cubeBody.position.y,cubeBody.position.z)cubeMesh.quaternion.set(cubeBody.quaternion.x,cubeBody.quaternion.y,cubeBody.quaternion.z,cubeBody.quaternion.w)sphereMesh.position.set(sphereBody.position.x,sphereBody.position.y,sphereBody.position.z)sphereMesh.quaternion.set(sphereBody.quaternion.x,sphereBody.quaternion.y,sphereBody.quaternion.z,sphereBody.quaternion.w)icosahedronMesh.position.set(icosahedronBody.position.x,icosahedronBody.position.y,icosahedronBody.position.z)icosahedronMesh.quaternion.set(icosahedronBody.quaternion.x,icosahedronBody.quaternion.y,icosahedronBody.quaternion.z,icosahedronBody.quaternion.w)torusKnotMesh.position.set(torusKnotBody.position.x,torusKnotBody.position.y,torusKnotBody.position.z)torusKnotMesh.quaternion.set(torusKnotBody.quaternion.x,torusKnotBody.quaternion.y,torusKnotBody.quaternion.z,torusKnotBody.quaternion.w)render()stats.update()}functionrender(){renderer.render(scene,camera)}animate()
Troubleshooting
geometry.attributes.position.array error : Property 'array' does not exist on type 'BufferAttribute | InterleavedBufferAttribute | GLBufferAttribute'
Since the addition of the GLBufferAttribute as a new type of BufferGeometry.attributes, it does not contain the array property. So, we now need to cast the attribute as THREE.BufferAttribute when we want to use a property or method of a BufferAttribute that isn't included in the GLBufferAttribute type.
const position = (geometry.attributes.position as THREE.BufferAttribute).array
const normals = (geometry.attributes.normal as THREE.BufferAttribute).array
const uvs = (geometry.attributes.uv as THREE.BufferAttribute).array