【发布时间】:2022-06-23 12:26:17
【问题描述】:
在 VR Canvas 中,指针位于屏幕中间。但很难确定它的确切位置。为了缓解这种情况,我们可以使用与射击游戏相同的十字准线。但是我们如何才能将 Crosshair 添加到使用 ThreeJS 和 React-three-fiber 的 React 应用程序中。
【问题讨论】:
标签: reactjs three.js react-three-fiber
在 VR Canvas 中,指针位于屏幕中间。但很难确定它的确切位置。为了缓解这种情况,我们可以使用与射击游戏相同的十字准线。但是我们如何才能将 Crosshair 添加到使用 ThreeJS 和 React-three-fiber 的 React 应用程序中。
【问题讨论】:
标签: reactjs three.js react-three-fiber
这是一个流行的答案:https://codepen.io/driezis/pen/jOPzjLG
这是我的自定义代码,请享受...
import {useFrame, useThree} from "@react-three/fiber";
import {useEffect, useRef} from "react";
import {Line, Vector3} from "three";
const Crosshair = () => {
const dot = useRef();
const lines = useRef();
const { camera } = useThree();
useFrame(() => {
const vector = new Vector3(0, 0, -0.8).unproject(camera);
dot.current.position.set(...vector.toArray());
lines.current.position.set(0, 0, -4);
})
const Line = (props) => {
const ref = useRef()
useEffect(() => {
if(ref.current){
ref.current.geometry.setFromPoints([props.start, props.end].map((point) => new Vector3(...point)));
}
});
return (
<line ref={ref}>
<bufferGeometry />
<lineBasicMaterial color="white"/>
</line>
)
}
return (
<group>
<group ref={lines}>
<Line start={[0.05,0,0]} end={[0.18,0,0]} />
<Line start={[0,0.05,0]} end={[0,0.18,0]} />
<Line start={[-0.05,0,0]} end={[-0.18,0,0]} />
<Line start={[0,-0.05,0]} end={[0,-0.18,0]} />
</group>
<mesh ref={dot}>
<sphereBufferGeometry args={[0.0005, 64, 32]} />
<meshBasicMaterial color={'red'} />
</mesh>
</group>
)
}
export default Crosshair;
【讨论】: