如何使用ThreeJS, React添加十字准星



在VR Canvas中,指针被放置在屏幕中间。但很难确定它的确切位置。为了缓解这种情况,我们可以像射击游戏一样使用十字准星。但是我们如何在使用了ThreeJS和React-three-fiber的React应用中添加一个十字准星呢?

下面是一个流行的答案: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());
camera.add(lines.current);
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;

最新更新