Skip to content


 Zabbix
 Grafana
 Prometheus
 React Three Fiber
 Threejs and TypeScript
 SocketIO and TypeScript
 Blender Topological Earth
 Sweet Home 3D
 Design Patterns Python
 Design Patterns TypeScript
   
 Course Coupon Codes
Three.js and TypeScript
Kindle Edition
$6.99 $9.99 Paperback 
$22.99 $29.99




Design Patterns in TypeScript
Kindle Edition
$6.99 $9.99 Paperback
$11.99 $19.99




Design Patterns in Python
Kindle Edition
$6.99 $9.99 Paperback
$11.99 $19.99




Change Mass Instanced Mesh

Working Example

Description

This is similar to the Change Mass Example, however many more boxes are created as an instancedMesh.

An instancedMesh is useful when creating many meshes that are identical. It can reduce the number of draw calls required by Threejs and WebGL to render the scene. However, this doesn't mean that physics will be processed any faster. Cannon Physics calculations will still be done on the CPU, and calculated individually for each box, despite the rendering of each frame being much faster.

The sample code below creates 512 Cannon Boxes, positioned accordingly, linked to an instancedMesh containing 512 Threejs Boxes. In order to link each mesh within the instancedMesh, to a cannon body, you can assign the at method from the API.

function InstancedBoxes() {
  const [ref, { at }] = useBox(
    (i) => ({
      args: [1, 1, 1],
      type: 'Dynamic',
      position: [
        Math.floor(i % 8) * 1.01 - 4,
        Math.floor((i / 64) % 64) * 1.01 + 4,
        Math.floor((i / 8) % 8) * 1.01 - 4,
      ],
    }),
    useRef()
  )

  return (
    <instancedMesh
      ref={ref}
      args={[undefined, undefined, 512]}
      onPointerDown={(e) => {
        e.stopPropagation()
        at(e.instanceId).mass.set(1)
      }}
    >
      <boxGeometry args={[1, 1, 1]} />
      <meshNormalMaterial />
    </instancedMesh>
  )
}