我有一个简单的Three.js场景,我想围绕它移动相机。相机不仅需要能够移动,而且还必须能够围绕某个对焦点改变角度。对焦点实际上是摄影机的位置,在渲染时,我实际上只是通过cameraBuff转换摄影机并将其放置在球体上,然后告诉它查看对焦点。

在移动相机之前,一切正常,我可以旋转相机及所有其他功能。但是,一旦我开始移动,似乎就坏了!在法线角度(垂直,0 cameraBuff点垂直于表面,就会发生问题。

这是我用来围绕焦点旋转cameraBuff矢量/点的代码:

//mouse.onDown* things are recorded once the mouse is initially pressed
theta = -((event.clientX - mouse.onDownPosition.x) * 0.5) + mouse.onDownTheta;
phi = ((event.clientY - mouse.onDownPosition.y) * 0.5) + mouse.onDownPhi;

phi = Math.min(180, Math.max(0, phi));

cameraBuff.x = radius * Math.sin(theta * Math.PI / 360 ) * Math.cos( phi * Math.PI / 360 );
cameraBuff.y = radius * Math.sin(phi * Math.PI / 360 );
cameraBuff.z = radius * Math.cos(theta * Math.PI / 360 ) * Math.cos( phi * Math.PI / 360 );


例如,将phi = Math.min(180, Math.max(0, phi));更改为phi = Math.min(160, Math.max(20, phi));后,一切正常,但我什至无法使相机垂直于表面或降低表面。

例如,当按下w时,将发生以下情况:

if (input.w)
{
    var speed = [game.direction.x*60, game.direction.z*60];

    game.camera.position.x -= speed[0]; //camera.position and focus are basically the same point all the time.
    game.focus.x -= speed[0];

    game.camera.position.z -= speed[1];
    game.focus.z -= speed[1];
}


方向的计算如下:

var c = Math.sqrt(cameraBuff.x*cameraBuff.x + cameraBuff.z*cameraBuff.z);
var rat = 1/c;

game.direction.x = cameraBuff.x*rat;
game.direction.z = cameraBuff.z*rat;


有人可以解释我的代码有什么问题吗?

最佳答案

3D相机需要一个向量,因此它知道如何倾斜相机。这通常是向上方向,并且是正Y向量。如果摄像机平行于向上方向,则不知道向上是什么,因此可以猜测,并且无法倾斜摄像机。要使相机倾斜,您需要修改向上方向。

我还没有使用Three.js,但是我认为您可以使用camera.up向量。

您也可以通过将角度限制为0.1

关于javascript - 相机放置在高 Angular 或低 Angular 时表现异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10802634/

10-12 00:17
查看更多