这称为Raycaster。可以通过使用 hook 在 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)
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个codesandbox,检查控制台以了解数组何时包含命中。
TLDR 实施:
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>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2434 次 |
| 最近记录: |