Skip to content

useTrimesh & Contact Materials

Description

To create a hoop shape that we can throw balls at, the useTrimesh is the best option. It allows inward-facing faces.

Working Example

<>

Do use it sparingly though since it is very CPU intensive to continually calculate real time physics against.

function TorusKnot({ args, ...props }) {
  const geometry = useMemo(() => new TorusGeometry(...args), [args])
  const [ref] = useTrimesh(() => ({
    args: [geometry.attributes.position.array, geometry.index.array],
    material: 'ring',
    ...props,
  }))

  return (
    <mesh ref={ref} castShadow>
      <torusGeometry args={args} />
      <meshStandardMaterial />
    </mesh>
  )
}

In order to give the appearance that the balls are bouncing of the ring, useContactMaterial was used to create a relationship between materials named as ring and bouncy.

For collisions involving those materials, a restitution of 0.45 is used.

useContactMaterial('ring', 'bouncy', {
    restitution: 0.45
})

function TorusKnot({ args, ...props }) {
    ...
    const [ref] = useTrimesh(() => ({
        ...
        material: 'ring',
        ...
    }))

  ...

function InstancedSpheres() {
    ...
    const [ref, { at }] = useSphere(() => ({
        ...
        material: 'bouncy'
    }))

This example also demonstrates creating many spheres using instancedMesh functionality.

GitHub Branch

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

Comments