【问题标题】:Update camera position based on rotation three.js基于旋转三.js更新相机位置
【发布时间】:2021-06-19 09:03:36
【问题描述】:

我正在尝试为某些东西构建一个快速演示,并且我需要在我的场景中朝着它所看的方向移动相机。它类似于指针锁定控件,但是我需要相机能够上下移动,以及向前/向后/向左/向右移动。目前我只是在旋转相机并将其添加到位置,但这不会向前移动相机(相对于相机),它似乎在相对于你的奇怪方向移动,并且该方向会根据在你看的地方。这是我当前的代码:

const rotation = this.internalCamera.rotation.toVector3();
const speed = 1;
this.internalCamera.position.add(
    new Vector3(
        rotation.x * speed,
        rotation.y * speed,
        rotation.z * speed
    )
);

我感觉这与三中的空间系统有关,但我不确定。我搞砸了什么?

【问题讨论】:

  • 我认为您正在考虑将 rotation.x .z 和 .y 作为坐标测量值,当它们是角度时,您需要获得正确的 x、y 和 z 分量您的相机方向矢量
  • 尝试以下任何一种:camera.translateZ( - distance )、camera.translateX( distance )、camera.translateY( distance )、camera.position.y += distance。

标签: javascript three.js


【解决方案1】:

您的矢量“旋转”表示角度而不是坐标测量值。您需要制作移动矢量,然后将其与相机方向的旋转矩阵相乘。

//x <- left/right  y <- up/down  z <- forward backward
const vector = new Vector(x, y, z);

//make matrices
const rotx = (new THREE.Matrix4).makeRotationX(camera.rotation.x);
const roty = (new THREE.Matrix4).makeRotationY(camera.rotation.y);
const rotz = (new THREE.Matrix4).makeRotationZ(camera.rotation.z);

//multiply all matrices together
const rotmat = rotx.multiply(roty).multiply(rotx).multiply(rotz);

//multiply vector by matrix
vector.applyMatrix4(rotmat);

//finally add the vector to position
camera.position.add(vector);

这应该可以工作,我也希望你不介意我缩短了一些变量以使其更易于编写和阅读,因此你必须将其调整为正确的变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 2015-01-30
    • 2013-09-10
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多