以三个j

时间:2016-06-30 09:13:50

标签: vector camera three.js

你如何沿着它所面对的轨迹从一个固定点前后移动一个摄像机?

我知道有几个控制脚本可以做到这一点,但我需要做一些自定义的事情,我无法分解他们的代码来计算如何隔离上述行为。

我已经看过this answer我认为解决了这个问题并提出了这个代码:

cameraPosition = camera.position
cameraRotation = new THREE.Vector3(camera.rotation._x, camera.rotation._y, camera.rotation._z)
newCamera = new THREE.Vector3().addVectors(cameraPosition, cameraRotation)
camera.position.set(newCamera.x, newCamera.y, newCamera.z)
camera.updateProjectionMatrix()

但这似乎将相机移动到一个圆圈而不是向后和向前移动。

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:3)

以下是更新camera.position.z的方法。使用W =转发,S =落后

var camera, scene, renderer, geometry, material, mesh;

init();
animate();

function init() {

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 500;
    scene.add(camera);

    geometry = new THREE.CubeGeometry(200, 200, 200);
    material = new THREE.MeshNormalMaterial();

    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize(window.innerWidth, window.innerHeight);
    
    document.body.appendChild(renderer.domElement);
    document.body.addEventListener( 'keydown', onKeyDown, false );

}

function animate() {

    requestAnimationFrame(animate);
    render();

}

function render() {
    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.02;

    renderer.render(scene, camera);
}

function onKeyDown(){
switch( event.keyCode ) {
   case 83: // up
   camera.position.z += 50;
   break;
   case 87: // down
   camera.position.z -= 50;
   break;
}
   
}
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>

答案 1 :(得分:3)

要向前或向后移动相机,请使用

camera.translateZ( - distance );

camera.translateZ( distance );

three.js r.78