three.js:限制相机的旋转

时间:2017-02-22 19:01:54

标签: three.js quaternions

我正在使用three.js,试图模拟真实世界的相机。因此,我想将其旋转轴沿x轴和y轴限制为90度。

有简单的方法吗?我当前的代码工作效果不是很好(当你试图同时移动相机超过X和Y边界时会发疯)

if(xRot != null && xRot != undefined){
    camera.rotateX(xRot);            
}

if(yRot != null && yRot != undefined){
    camera.rotateY(yRot);
}

if(camera.rotation.x < minCameraRotX){
    camera.rotation.x = minCameraRotX;
}else if (camera.rotation.x > maxCameraRotX){
    camera.rotation.x = maxCameraRotX;
}     

if(camera.rotation.y < minCameraRotY){
    camera.rotation.y = minCameraRotY;
}else if(camera.rotation.y > maxCameraRotY){
    camera.rotation.y = maxCameraRotY;
}  

任何建议都将非常感谢!!!

1 个答案:

答案 0 :(得分:1)

我实际上通过检查一个名为PointerLock的库的Three.js演示中的一些现有代码来设法找到解决方案。这个想法是实际上将多个物体堆叠在一起:从一个水平移动的物体(偏航物体)开始,将另一个物体放在垂直移动的偏航物体内(俯仰物体),然后将实际相机放在物体内对象

然后,您只能沿着各自的轴旋转外部物体(偏航和俯仰),因此如果您同时旋转它们,它们将自我纠正。例如,如果您将偏航沿y轴旋转45度(使其向右转)然后将俯仰旋转45度(使其向下转动),俯仰将从偏航向下倾斜45度 #39;已经旋转的位置。

鉴于摄像头位于两者内部,它只指向偏航和俯仰的任何地方。

这是代码

&#13;
&#13;
/*
 * CAMERA SETUP
 *
 * Root object is a Yaw object (which controls horizontal movements)
 * Yaw object contains a Pitch object (which controls vertical movement)
 * Pitch object contains camera (which allows scene to be viewed)
 *
 * Entire setup works like an airplane with a 
 * camera embedded in the propellor...
 *
 */

// Yaw Object
var yawObject = new THREE.Object3D();

// Pitch Object
var pitchObject = new THREE.Object3D();    

// Camera Object
var camera = new THREE.PerspectiveCamera(fov, aspect, near, far);

// Max Camera angles (in radians)
var minCameraRotX = 0.5;
var maxCameraRotX = 0.5;
var minCameraRotY = 1;
var maxCameraRotY = 1;


// Setup
yawObject.add( pitchObject );
pitchObject.add( camera );

scene.add(yawObject);

...

var rotateCamera = function(xRot, yRot, zRot){
    yawObject.rotation.y += yRot;
    pitchObject.rotation.x += xRot;

    // Enforce X-axis boundaries (rotates around y-axis)
    yawObject.rotation.y = Math.max( minCameraRotY, Math.min( maxCameraRotY, yawObject.rotation.y ) );

    // Enforce Y-axis boundaries (rotates around x-axis)
    pitchObject.rotation.x = Math.max( minCameraRotX, Math.min( maxCameraRotX, pitchObject.rotation.x ) );
}
&#13;
&#13;
&#13;

以下是我引用的源代码:https://github.com/mrdoob/three.js/blob/acda8a7c8f90ce9b71088e903d8dd029e229678e/examples/js/controls/PointerLockControls.js

此外,这有点俗气,但是这个小飞机卡通让我直观地了解了我的设置enter image description here