Three.js使用OrbitControls后修改相机旋转方向无效

1.问题复现

        在项目中添加了OrbitControls控制器来控制相机的旋转和平移,但是需要修改初始的相机角度,于是我把相机的角度进行修改,如下:

const camera = new THREE.PerspectiveCamera(75, viewport.offsetWidth / viewport.offsetHeight, 0.01, 20);
camera.position.set(0,1,7);
//修改相机初始角度
camera.rotation.set(0,-Math.PI/2,0);
const controls = new OrbitControls(camera, renderer.domElement);
controls.update();

运行项目后发现相机的位置并没有发生变化。原因是相机旋转和移动被OrbitControls控制器托管了。

2.解决方法

        于是我尝试创建一个组,将相机加入组里,通过改变组的旋转角度从而改变相机的初始角度,如下:

	const cameraRigY = new THREE.Group();
	scene.add(cameraRigY);

    const camera = new THREE.PerspectiveCamera(75, viewport.offsetWidth / viewport.offsetHeight, 0.01, 20);
	camera.position.set(0,1,7);
    //相机加入组里
	cameraRigY.add(camera);
	//修改整体相机Y轴旋转
	cameraRigY.rotation.set(0,Math.PI/2,0);

	const controls = new OrbitControls(camera, renderer.domElement);
	controls.update();

进过测试,相机的初始角度修改成功了。

3.重置相机

        在相机旋转操作了之后,想重置到原来的状态,发现上诉方法也无效了。而OrbitControls控制器提供了两个方法来实现:

     /**
     * Save the current state of the controls. This can later be
     * recovered with .reset.
     */
    saveState(): void;

    /**
     * Reset the controls to their state from either the last time
     * the .saveState was called, or the initial state.
     */
    reset(): void;

先调用saveState()方法保存当前的相机状态,然后使用reset()方法重置到之前保存的状态即可。

猜你喜欢

转载自blog.csdn.net/qq_26540577/article/details/131596399