使用three.js相机时出现问题

时间:2016-02-23 19:28:54

标签: javascript camera three.js

我无法弄清楚如何使用three.js相机。

What i'm trying to achieve

这基本上是我要实现的目标。我有一个小地图,玩家可以在其角落产生(这里,它们被表示为立方体),在草图上由1,2,3和4表示。

我希望相机在启动时位于它们后面,由" eye"在我的草图上,指向立方体1的中心,橙色线代表视线。如果我是第四位玩家,我也会按照我的要求画出相机的位置。

但它会在之后发生。在测试期间,我面临着一种我不期待的行为。让我解释一下,这就是我目前正在做的事情:

camera.position.set(player.position.x, player.position.y + 2, player.position.z + 3);
camera.lookAt(player.position);

player变量是THREE.Mesh。相机应放置在播放器的顶部,如果播放器产生1或3,它会按预期工作,但在2中,它绝对错误:当我用鼠标移动它时它绕着它旋转,就像在Y轴上旋转一样,我永远看不到我的立方体...我认为我在我的播放器上使用lookAt()方法的事实让我可以用我的指向它相机,但显然我错了。

有人可以解释一下为什么它没有按预期工作吗?

1 个答案:

答案 0 :(得分:0)

很难说没有查看你的代码,但这里有一个样本做你所描述的,它也调用了一个带有键x,y和z的对象的lookAt ......

http://jsfiddle.net/vn4t6o6u/1/

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);

    // Place camera on x axis

    scene.add(camera);
        camera.position.set(-6,-6,30);
    camera.up = new THREE.Vector3(0,0,1);    
    camera.lookAt({x:0,y:0,z:0});
    setTimeout(function(){
            camera.position.set(14,-6,30);
        camera.lookAt({x:8,y:0,z:0});  
    }, 1000)
    setTimeout(function(){
            camera.position.set(-6,14,30);
        camera.lookAt({x:0,y:8,z:0});  
    }, 2000)
    setTimeout(function(){
            camera.position.set(14,14,30);
        camera.lookAt({x:8,y:8,z:0});  
    }, 3000)

    geometry1 = new THREE.CubeGeometry(2, 2, 2);
    geometry2 = new THREE.CubeGeometry(2, 2, 2);
    geometry3 = new THREE.CubeGeometry(2, 2, 2);
    geometry4 = new THREE.CubeGeometry(2, 2, 2);

    material1 = new THREE.MeshLambertMaterial({color: 0xff0000});
    material2 = new THREE.MeshLambertMaterial({color: 0x00ff00});
    material3 = new THREE.MeshLambertMaterial({color: 0x0000ff});
    material4 = new THREE.MeshLambertMaterial({color: 0x00ffff});

    mesh1 = new THREE.Mesh(geometry1, material1);
    mesh2 = new THREE.Mesh(geometry2, material2);    
    mesh3 = new THREE.Mesh(geometry3, material3);    
    mesh4 = new THREE.Mesh(geometry4, material4);    

    mesh1.position.set(0, 0, 0);
    mesh2.position.set(8, 0, 0);
    mesh3.position.set(0, 8, 0);
    mesh4.position.set(8, 8, 0);

        scene.add(mesh1);
    scene.add(mesh2);
    scene.add(mesh3);
    scene.add(mesh4);

    renderer = new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);

    document.body.appendChild(renderer.domElement);

}

function animate() {

    requestAnimationFrame(animate);
    render();

}

function render() {




    renderer.render(scene, camera);

}