javascript - 三JS : Getting the rotation so one vector3 will face another vector3

标签 javascript matrix three.js rotation quaternions

我开始了解 ThreeJS 以及它带来的所有乐趣。我将 ThreeJS 与 aframe 一起使用。当前任务需要使用 ThreeJS 进行计算,以便我可以将位置和旋转传递给 aframe 组件。我读过其他帖子,但大多数都是 C++。我可以遵循代码,但他们似乎没有使用四元数或 ThreeJS。

我在 0,0,0 处有一个相机,我想将其旋转到空间中的特定点。最终,将会有很多点,它们将由用户保存、加载、编辑。矩阵数组似乎是保存这些信息的好方法。选择一个点后,我需要旋转相机,使其面向该方向。最终用户能够更改事件点,从而更改相机的旋转。

// I want to get the rotation from the camera to the result of a raycast
const camera = new Vector3()
const cast = new Vector3(10, 0, -20)

// I created a quaternion from my vectors to 
// get the rotation from the camera to the cast
const quaternion = new Quaternion().setFromUnitVectors(camera, cast)
console.info('quaternion', quaternion.toArray())
// this is always [-0, 0, 0, 1] regardless of my x, y, z for cast

// I use the quaternion to create a new Matrix4
const matrix = new Matrix4().makeRotationFromQuaternion(quaternion)
// This is always the same
//  Makes sense since the quaternion is always the same
console.log(matrix.toArray())

const position = matrix.getPosition() // Vector3(0, 0, 0)
// This just creates another matrix
// I do not know how to get the rotation
const rotation = new Matrix4().extractRotation(matrix)

我的处理方式正确吗? x、y、z 和 w 的四元数属性始终相同。我知道到那时有些事情已经搞砸了。

回顾一下我的问题:

  1. 为什么无论提供的 x、y、z 值如何,四元数始终相同?
  2. 如何使四元数实际上成为旋转相机所需的旋转?
  3. 如何从 Matrix4 中获得旋转?

这几天一直在试图理解这一点。因此,如果我错过了一些简单的事情,请大家道歉。

谢谢

约旦

最佳答案

如果你只是想让相机面向你的点,则 Three.js 中有一个函数,camera.lookAt(point)。如果你想获得旋转但不旋转相机,你可以使用这些代码:

    var matrix = new THREE.Matrix4();
    matrix.lookAt(camera.position,point,camera.up);
    var rotation = new THREE.Euler(0,0,0,"XYZ");
    rotation.setFromRotationMatrix(rotation);

现在旋转将是从相机到目标点的旋转,您知道旋转的类型是THREE.Euler,因此,您可以使用以下方法设置旋转THREE.Euler.setFromRotationMatrix()

我对四元数不太了解,其实是用 Three.js 中的matrix4实现的四元数。我认为矩阵4可以做四元数能做的任何事情。

关于javascript - 三JS : Getting the rotation so one vector3 will face another vector3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43357483/

相关文章:

javascript - 将 Three.js 骨骼动画更新到新的基于混合器的系统

javascript - 用条件替换字符串中的 url

将一个向量提升为另一个向量的幂

javascript - ThreeJS透明PNG纹理黑色

c++ - 无法正确生成 ViewProjection 矩阵

c++ - 将固定大小的特征矩阵作为参数传递给调用动态大小矩阵的函数

javascript - 单击时使用 Raycaster 更改 Box 面的颜色

javascript - Angular UI Bootstrap Datepicker 动态日期(可变)

javascript - 如何使我的 .css 和 .js 文件与 Android 上的 WebView 中加载的 html 代码一起使用

javascript - 如何让我的 chrome 扩展程序记住拨动开关或其他操作?