【问题标题】:Three.js: Camera flying around sphere?Three.js:相机在球体周围飞行?
【发布时间】:2012-06-17 07:25:23
【问题描述】:

在 Three.js(使用 JavaScript/WebGL)中,如何创建一个以固定高度、固定前进速度和相对于球体的固定方向围绕球体飞行的相机,而用户只能左右转向?

想象一架飞机在一个看不见的绳子上指向地球中心,在地面附近飞行,并且总是看到球体的一部分:

(我目前有代码可以旋转球体,使相机看起来像是在飞行——左右转向尚未实现——但我认为在进一步之前,移动相机/飞机可能会更干净,不是球体组。)

谢谢!

【问题讨论】:

  • 创建两个空组并将相机放入其中 - forwardCamGroup(sidewaysCamGroup(camera)) - 工作几秒钟,但随后旋转继续(forwardCamGroup.rotation.x -= .0025; sidewaysCamGroup.rotation.y += .0025;) 侧向转向变得像向后转向一样倾斜......
  • 我现在得到了一些东西,但它看起来更像是横向移动,而不是横向旋转:/ camGroup.matrix.rotateY(app.mouseXPercent *.00025); camGroup.matrix.rotateX(-.0025); camGroup.rotation.getRotationFromMatrix(camGroup.matrix);
  • (好的,如下解决!)

标签: javascript three.js


【解决方案1】:

你的意思是像我的Ludum Dare 23 game?我发现这比我预期的要复杂一些。不过这并不难。

这里我假设你知道相机的纬度和经度以及它与球体中心的距离(称为radius),并想为相机创建一个变换矩阵。

以下对象只创建一次,以避免在游戏循环中创建新对象:

var rotationY = new Matrix4();
var rotationX = new Matrix4();
var translation = new Matrix4();
var matrix = new Matrix4();

那么每次相机移动时,创建矩阵如下:

rotationY.setRotationY(longitude);
rotationX.setRotationX(-latitude);
translation.setTranslation(0, 0, radius);
matrix.multiply(rotationY, rotationX).multiplySelf(translation);

之后只需设置相机矩阵(假设相机是您的相机对象):

// Clear the camera matrix.
// Strangely, Object3D doesn't have a way to just SET the matrix(?)
camera.matrix.identity();
camera.applyMatrix(matrix);

【讨论】:

    【解决方案2】:

    感谢马丁的回答!我现在用另一种方法让它运行良好,如下所示(Martin 的方法可能也很完美;也非常感谢 Lmg!):

    在开始时将相机设置为球体顶部的直线(即高 y 值,略超出半径,在我的情况下为 200);让它看起来低一点:

    camera.position.set(0, 210, 0);
    camera.lookAt( new THREE.Vector3(0, 190, -50) );
    

    创建一个空组(一个Object3D)并将相机放入:

    camGroup = new THREE.Object3D();
    camGroup.add(camera);
    scene.add(camGroup);
    

    以百分比形式跟踪鼠标相对于半屏的位置:

    var halfWidth = window.innerWidth / 2, halfHeight = window.innerHeight / 2;
    app.mouseX = event.pageX - halfWidth;
    app.mouseY = event.pageY - halfHeight;
    app.mouseXPercent = Math.ceil( (app.mouseX / halfWidth) * 100 );
    app.mouseYPercent = Math.ceil( (app.mouseY / halfHeight) * 100 );
    

    在动画循环中,将此百分比应用于旋转,同时自动向前移动:

    camGroup.matrix.rotateY(-app.mouseXPercent * .00025);
    camGroup.matrix.rotateX(-.0025);
    camGroup.rotation.getRotationFromMatrix(camGroup.matrix);
    
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-17
      • 2012-08-07
      • 2019-07-12
      • 2012-12-11
      • 2017-02-21
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      相关资源
      最近更新 更多