javascript - 获取节点层次结构中的节点面向相机(广告牌)

标签 javascript quaternions rotational-matrices euler-angles

我需要使节点层次结构中的一个节点面向相机,或者换句话说,成为一个广告牌。 对于每个节点,我将其世界矩阵和世界旋转存储为四元数。 根据我对四元数的了解,我想要的操作是获取相机四元数和节点的旋转四元数之间的差值,然后简单地旋转节点该差值。

我的相机存储为欧拉 Angular ,因此我通过首先创建 X 轴旋转,然后创建 Z 轴旋转(我没有 Y 轴旋转)并将它们相乘来构造相机四元数。

从这里开始,只需进行一些数学运算即可获得差异,最后从中创建一个旋转矩阵,并将节点的世界矩阵与其相乘。

然而,这最终导致节点像疯狂的暴徒一样旋转,并且绝不面向相机。

以下是相关的 JavaScript 代码:

// If there is a parent, multiply both world matrix and rotation by it
// localMatrix here is the current local matrix of the node
// rotation here is the local rotation quaternion
if (node.parent) {
    math.Mat4.multMat(node.parent.worldMatrix, localMatrix, node.worldMatrix);
    math.Quaternion.concat(node.parent.worldRotation, rotation, node.worldRotation);
} else {
    node.worldMatrix = localMatrix;
    node.worldRotation = rotation.copy();
}

// And here the mess begins
if (node.billboarded) {
    var cameraX = [];
    var cameraZ = [];
    var camera = [];

    // transform.rotation is my camera's rotation stored as 3 euler angles,
    // but I am not using the Y-axis for now
    math.Quaternion.setFromAxisAngle([1, 0, 0], transform.rotation[0], cameraX);
    math.Quaternion.setFromAxisAngle([0, 0, 1], transform.rotation[2], cameraZ);
    math.Quaternion.concat(cameraX, cameraZ, camera);

    // The current rotation on the node
    var initial = node.worldRotation.copy();

    // Need to reverse it, since the difference is camera * -initial
    math.Quaternion.conjugate(initial, initial);

    var difference = [];

    math.Quaternion.concat(camera, initial, difference);

    var rotationMatrix = [];

    math.Quaternion.toRotationMatrix4(difference, rotationMatrix);

    var finalMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];

    // pivot is the node's position, need to keep the rotation in local space
    math.Mat4.translate(finalMatrix, pivot[0], pivot[1], pivot[2]);
    math.Mat4.multMat(finalMatrix, rotationMatrix, finalMatrix);
    math.Mat4.translate(finalMatrix, -pivot[0], -pivot[1], -pivot[2]);

    // And finally actually rotate the node
    math.Mat4.multMat(node.worldMatrix, finalMatrix, node.worldMatrix);
}

我犯了一些明显的错误吗?

最佳答案

你的假设是错误的:

the operation I want is to get the difference between the camera quaternion and the rotation quaternion of a node, and simply rotate the node by said difference.

如果你这样做正确,它应该会导致你的节点面向与相机面向相同的方向。这与实际面对相机有很大不同。

您需要找到面向世界空间中相机位置的变换。您可能会受益于对 gluLookAt() 的一些快速研究。

关于javascript - 获取节点层次结构中的节点面向相机(广告牌),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17258087/

相关文章:

javascript - 为什么 isNaN(123.) 返回 false?

javascript - 如何在 Jasmine 中测试 Sequelize?

c# - Unity3D Slerp旋转速度

math - 连续坐标旋转中的浮点误差

javascript - Node async.js 多重功能与 waterfall

javascript - 带有基本 href 和查询字符串的 jQuery ui 选项卡不起作用

c++ - 使用四元数 boost QVM 旋转

c++ - Eigen C++/Matlab 四元数和旋转矩阵不匹配

c++ - findHomography()中得到的矩阵的单应分解