如何在Three.js中拖动鼠标来改变相机位置?

时间:2012-12-27 15:52:28

标签: javascript webgl three.js

我制作了劳力士立方体的几何形状,每层之间的“Z轴”不同。现在我想改变相机的位置,以便我可以检查几何形状正是我所期待的。我的问题是如何在拖动窗口时更改摄像机位置,还应该能够根据鼠标事件操纵每个锥体的旋转。

这是我的jsfiddle链接:http://jsfiddle.net/sagh0900/gfraQ/8/

示例代码,但请确保您访问jsfiddle以获取我的问题的详细信息:

for ( var i = 0; i <nSize; i++)
{
    var k = i%10,
        j = (i-k)/10;

    j = j*2 - 10;
    k = k*2 - 10;

    var cone1 = lc_relationship.sensor1[i].Geometry; 
    scene.add(cone1);
    var cone2 = lc_relationship.sensor2[i].Geometry;
    scene.add(cone2);
    var cone3 = lc_relationship.sensor3[i].Geometry;
    scene.add(cone3);
    cone1.position.set(j, k, lc_relationship.sensor1[i].z_cordinate);
    cone2.position.set(j, k, lc_relationship.sensor2[i].z_cordinate);
    cone3.position.set(j, k, lc_relationship.sensor3[i].z_cordinate);
}

如果有人可以更新我的jsfiddle或为我提供帮助就足够了。

提前致谢。

1 个答案:

答案 0 :(得分:1)

我使用空(null)网格来添加对象而不是scene:Mesh

mesh = new THREE.Mesh(new THREE.Geometry());
scene.add(mesh);
/*[...]*/
mesh.add(cone1);
/*[...]*/
mesh.add(cone2);
/*[...]*/
mesh.add(cone3);
/*[...]*/

并添加此项以旋转此网格:

var screenW = window.innerWidth;
var screenH = window.innerHeight; /*SCREEN*/
var spdx = 0, spdy = 0; mouseX = 0, mouseY = 0, mouseDown = false; /*MOUSE*/
document.addEventListener('mousemove', function(event) {
    mouseX = event.clientX;
    mouseY = event.clientY;
}, false);
document.body.addEventListener("mousedown", function(event) {
    mouseDown = true
}, false);
document.body.addEventListener("mouseup", function(event) {
    mouseDown = false
}, false);
function animate() {    
    spdy =  (screenH / 2 - mouseY) / 40;
    spdx =  (screenW / 2 - mouseX) / 40;
    if (mouseDown){
        mesh.rotation.x = spdy;
        mesh.rotation.y = spdx;
    }
}

测试:http://jsfiddle.net/gfraQ/11/