Skip to content

Change Mass Instanced Mesh

Working Example

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>
  )
}
Change Mass Instanced Mesh (Working Example) sbedit.net

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout changeMassInstanced
npm install
npm start

Comments