Changing the camera rotation direction after using OrbitControls in Three.js is invalid

1. Problem recurrence

        The OrbitControls controller is added to the project to control the rotation and translation of the camera, but the initial camera angle needs to be modified, so I modify the camera angle as follows:

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();

After running the project, it is found that the position of the camera has not changed. The reason is that camera rotation and movement is managed by the OrbitControls controller.

2. Solution

        So I tried to create a group, add the camera to the group, and change the initial angle of the camera by changing the rotation angle of the group, as follows:

	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();

After testing, the initial angle modification of the camera was successful.

3. Reset the camera

        After the camera was rotated, I wanted to reset it to the original state, but found that the appeal method was also invalid. The OrbitControls controller provides two methods to achieve:

     /**
     * 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;

First call the saveState() method to save the current camera state, and then use the reset() method to reset to the previously saved state.

Guess you like

Origin blog.csdn.net/qq_26540577/article/details/131596399