如何在React Three Fiber中进行简单的碰撞检测

3

我不想使用任何库,我只需要简单的碰撞检测。如果是在对象移动方向上的射线投射,那就可以了。

我不知道从哪里开始编写这个代码。

1个回答

5
这被称为射线投射器。它可以通过使用钩子在react-three-fiber中实现:
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)
  }
}

这里有一个codesandbox,查看控制台以了解数组包含命中时的情况。

简化实现:

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>
  )
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接