首页 > 解决方案 > ThreeJS - 沿样条线移动相机,同时保持轨道控制平移

问题描述

THREE.CatmullRomCurve3我有一个带有一堆点的样条实例。使用鼠标滚轮时,我可以在样条曲线上上下移动相机。

但是,在样条曲线上设置相机位置时,我失去了 OrbitControls 旋转/平移。我想用鼠标沿着样条线移动相机,同时仍然能够用光标环顾四周。

任何人都知道如何做到这一点?下面是一些重要的代码:

// Increment/Decrement number when scrolling via mouse wheel
let camPosIndex = 0;

canvas.addEventListener('wheel', (e) => {
    camPosIndex += -Math.sign(e.deltaY) * 0.1;
    if (camPosIndex < 0) {
        camPosIndex = 0;
    }
});
// Animation loop
tick() {
    // Update camera around spline
    if (camera && cameraSplinePoints.length > 0 && cameraSpline) {
        const camPos = cameraSpline.getPoint(camPosIndex / 100);
        const camRot = cameraSpline.getTangent(camPosIndex / 100);

        camera.position.x = camPos.x;
        camera.position.y = camPos.y;
        camera.position.z = camPos.z;

        camera.rotation.x = camRot.x;
        camera.rotation.y = camRot.y;
        camera.rotation.z = camRot.z;

        // Somewhere above or below, the camera is now ignoring the orbitcontrols panning.

        camera.lookAt(cameraSpline.getPointAt((camPosIndex+1) / 100));
    }

    // Update controls
    controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

标签: canvasthree.jscameracontrolsspline

解决方案


我可以通过将目标设置为相机位置并朝其方向看来计算它。

在我的渲染循环中,我通过以下方式设置位置和旋转:

controls.object.position.set(camPos.x, camPos.y, camPos.z);

controls.target = new THREE.Vector3().addVectors(
    controls.object.position,
    controls.object.getWorldDirection()
);

推荐阅读