THREEJS:在看的同时旋转相机

时间:2013-05-13 21:38:24

标签: camera rotation three.js

我有一个移动相机在相机容器中飞行在现场像飞机一样的路径;所以它可以移动到任何位置x,y,z正面和负面。相机容器使用样条曲线查看自己未来的路径。

现在我想使用鼠标方向旋转相机,但仍然保持一般看向位置,同时向前移动物体。你可以说,我想把我的头转向我的身体:在移动身体一般看着方向的同时,我转过头来让我说上下220度。所以我无法看到身体后面。

在我的代码中,cameraContainer负责在pline曲线上移动并查看移动方向。相机作为一个孩子添加到cameraContainer,负责使用鼠标旋转。

我无法正常工作的是相机的旋转。我想这是一个非常普遍的问题。让我们说相机只在x轴上移动时不会移动,它会像曲线一样移动。特别是在不同的相机位置,旋转看起来非常不同。我试图使用cameraContainer来避免这个问题,但问题似乎与世界坐标无关。

这就是我所拥有的:

// camera is in a container
cameraContainer = new THREEJS.Object3D();
cameraContainer.add(camera);
camera.lookAt(0,0,1);
cameraContainer.lookAt(nextPositionOnSplineCurve);


// Here goes the rotation depending on mouse
// Vertical
var mouseVerti = 1;     // 1 = top, -1 = bottom
if(window.App4D.mouse.y <= instance.domCenterPos.y)             // mouse is bottom?
    mouseVerti = -1;

// how far is the mouse away from center: 1 most, 0 near
var yMousePerc = Math.abs(Math.ceil((instance.domCenterPos.y - window.App4D.mouse.y) / (instance.domCenterPos.y - instance.domBoundingBox.bottom) * 100) / 100);
var yAngleDiffSide = (instance.config.scene.camera.maxAngle - instance.config.scene.camera.angle) / 2;
var yRotateRan = mouseVerti * yAngleDiffSide * yMousePerc * Math.PI / 180;
instance.camera.rotation.x += yRotateRan;       // rotation x = vertical


// Horizontal
var mouseHori = 1;      // 1 = top, -1 = bottom
if(window.App4D.mouse.x <= instance.domCenterPos.x)             // mouse is left?
    mouseHori = -1;

// how far is the mouse away from center: 1 most, 0 near
var xMousePerc = Math.abs(Math.ceil((instance.domCenterPos.x - window.App4D.mouse.x) / (instance.domCenterPos.x - instance.domBoundingBox.right) * 100) / 100);
var xAngleDiffSide = (instance.config.scene.camera.maxAngle - instance.config.scene.camera.angle) / 2;
var xRotateRan = mouseHori * xAngleDiffSide * xMousePerc * Math.PI / 180;
instance.camera.rotation.y += xRotateRan;       // rotation y = horizontal

如果有人能给我一个提示,真的会感激不尽!

1 个答案:

答案 0 :(得分:1)

经过一些试验和错误,我得到了答案。解决方案是简单地考虑y的初始旋转。

当将相机容器和真实相机设置为容器的子容器时,我必须将相机对准相机容器对象的前面,以使相机朝向正确的方向。这导致初始旋转0,3.14,0(x,y,z)。每次我指定(如WestLangley所述)鼠标旋转时,解决方案是在y旋转中添加3.14。

cameraReal.lookAt(new THREE.Vector3(0,0,1));
cameraReal.rotation.y = xRotateRan + 3.14;