通过改变useFrame中的位置来移动对象不起作用



我有一个代码如下。虽然我在每一帧(useFrame)中更新球体位置,但它不会反映在我的场景中。有人能帮我理解为什么它不能工作吗?

PS:我是新手,正试图做一些快速的概念证明。

function Marble() {
const controls = useControls()
const [sphereRef, sphereApi] = useSphere(() => ({
type: "Dynamic",
mass: 1,
position: [0, 2, 0]
}));

//sphereApi.position.set([0,0,0])
//console.log("SHM sphereAPI position", sphereRef.current.position);
useFrame(() => {
const { forward, backward, left, right, brake, reset } = controls.current
if (forward == true) {
console.log("sphereRef position", sphereRef.current.position);
console.log("sphereAPI position", sphereApi.position);
//console.log("model position", model.current.position)
// sphereApi.velocity.set(2,2,2);
sphereApi.position.set(5,0,0)
// sphereRef.current.position.set(5,0,0);
}
})
return (
<mesh ref={sphereRef} castShadow>
<sphereBufferGeometry attach="geometry" args={[1, 32, 32]}></sphereBufferGeometry>
<meshStandardMaterial color="white" />
</mesh>
);
})

(参见在线:Stackblitz)

在每一帧中执行sphereApi.position.set(5,0,0),只是在每一帧中将球体位置设置为x=5

所以你应该首先创建一个状态来存储x位置,然后在每一帧更新它到+=5,然后将球体位置设置为:
const [sphereX, setSphereX] = useState(0);
useFrame(() => {
setSphereX((sphereX) => sphereX + 0.05); // set state x position to +0.05 (5 is fast)
sphereApi.position.set(sphereX, 0, 0); // apply the state to the sphere position
});

还要确保使用allowSleep={false},因为直接改变位置不是物理运动,所以物理场景可能会进入睡眠状态。

在线:Stackblitz