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




useTrimesh & Contact Materials

Working Example

Description

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

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.