Search code examples
react-three-fiber

how to do simple collision detection in react three fiber


I don't want to use any libraries. I just want simple collision detection. If it's a raycast in the direction the object is moving I am happy with that.

I don't know where to begin to write code for this.


Solution

  • This is called a Raycaster. It can be implemented in react-three-fiber by using a hook:

    import { useThree } from '@react-three/fiber'
    import { useMemo } from 'react'
    import { Object3D, Raycaster, Vector3 } from 'three'
    
    export const useForwardRaycast = (obj: {current: Object3D|null}) => {
    
      const raycaster = useMemo(() => new Raycaster(), [])
      const pos = useMemo(() => new Vector3(), [])
      const dir = useMemo(() => new Vector3(), [])
      const scene = useThree(state => state.scene)
    
      return () => {
        if (!obj.current)
          return []
        raycaster.set(
          obj.current.getWorldPosition(pos),
          obj.current.getWorldDirection(dir))
        return raycaster.intersectObjects(scene.children)
      }
    }
    

    Here's a codesandbox, check out the console for when the array contains hits.

    TLDR implementation:

    const Comp = () => {
      const ref = useRef(null)
      const raycast = useForwardRaycast(ref)
      useFrame((state, delta) => {
        ref.current.rotation.y += 1 * delta
        const intersections = raycast()
        console.log(intersections.length)
        //...do something here
      })
    
      return (
        <mesh ref={ref}>
          <boxGeometry />
          <meshStandardMaterial color="orange" />
        </mesh>
      )
    }