我正在尝试将相机旋转到场景的X轴。
此时我的代码是这样的:
rotation += 0.05;
camera.position.y = Math.sin(rotation) * 500;
camera.position.z = Math.cos(rotation) * 500;
这会让相机四处移动,但在旋转过程中会发生奇怪的事情,相机会翻转,或者它会跳过它所跟随的假想圆圈的某些部分。
答案 0 :(得分:5)
您只提供了一段代码,因此我必须对您正在做的事情做出一些假设。
此代码:
rotation += 0.05;
camera.position.x = 0;
camera.position.y = Math.sin(rotation) * 500;
camera.position.z = Math.cos(rotation) * 500;
camera.lookAt( scene.position ); // the origin
会引起你所指的“翻转”,因为相机试图保持“正面向上”,并且当它经过“北极”时它会迅速改变方向。
如果像这样偏移相机的x坐标,
camera.position.x = 200;
相机的行为对你来说会更自然。
答案 1 :(得分:3)
Three.js试图让相机朝上。当您沿z轴传递0时,它将“修复”相机的旋转。您可以手动检查并重置摄像机的角度。
camera.lookAt( scene.position ); // the origin
if (camera.position.z < 0) {
camera.rotation.z = 0;
}
我确信这不是最好的解决方案,但是如果其他人在玩three.js时遇到这个问题(就像我刚才那样),它会更进一步。
答案 2 :(得分:0)
我想在让照相机注视特定对象的同时将照相机移至新位置,这就是我想出的[请确保加载tween.js]:
/**
* Helper to move camera
* @param loc Vec3 - where to move the camera; has x, y, z attrs
* @param lookAt Vec3 - where the camera should look; has x, y, z attrs
* @param duration int - duration of transition in ms
**/
function flyTo(loc, lookAt, duration) {
// Use initial camera quaternion as the slerp starting point
var startQuaternion = camera.quaternion.clone();
// Use dummy camera focused on target as the slerp ending point
var dummyCamera = camera.clone();
dummyCamera.position.set(loc.x, loc.y, loc.z);
// set the dummy camera quaternion
var rotObjectMatrix = new THREE.Matrix4();
rotObjectMatrix.makeRotationFromQuaternion(startQuaternion);
dummyCamera.quaternion.setFromRotationMatrix(rotObjectMatrix);
dummyCamera.up.set(camera)
console.log(camera.quaternion, dummyCamera.quaternion);
// create dummy controls to avoid mutating main controls
var dummyControls = new THREE.TrackballControls(dummyCamera);
dummyControls.target.set(loc.x, loc.y, loc.z);
dummyControls.update();
// Animate between the start and end quaternions
new TWEEN.Tween(camera.position)
.to(loc, duration)
.onUpdate(function(timestamp) {
// Slerp the camera quaternion for smooth transition.
// `timestamp` is the eased time value from the tween.
THREE.Quaternion.slerp(startQuaternion, dummyCamera.quaternion, camera.quaternion, timestamp);
camera.lookAt(lookAt);
})
.onComplete(function() {
controls.target = new THREE.Vector3(scene.children[1].position-0.001);
camera.lookAt(lookAt);
}).start();
}
用法示例:
var pos = {
x: -4.3,
y: 1.7,
z: 7.3,
};
var lookAt = scene.children[1].position;
flyTo(pos, lookAt, 60000);
然后在您的update()/render()
函数中,调用TWEEN.update();
答案 3 :(得分:0)
这对我有用,希望对您有所帮助。
var axis = new THREE.Vector3( 1, 0, 0 );
var quaternion = new THREE.Quaternion;
camera.position.applyQuaternion(quaternion.setFromAxisAngle(axis, rotation_speed));
camera.up.applyQuaternion(quaternion.setFromAxisAngle(axis, rotation_speed));