基于四元数的火炮本体正确旋转处理

Handling Proper Rotation of Cannon Body Based on Quaternion?

本文关键字:旋转 处理 四元数      更新时间:2023-09-26

这个问题让我很困扰。我正在尝试实现大炮的旋转。基于鼠标输入的主体。通过(加农炮)三帧FPS的例子,你可以看到问题所在。

https://codepen.io/Raggar/pen/EggaZPhttps://github.com/RaggarDK/Baby/blob/baby/pl.js

当你运行代码并通过点击"点击播放"区域并按W 1秒使球体进入相机视图时,你会看到球体通过应用速度根据WASD键移动。如果移动鼠标,四元数将应用于Body,并计算适当的速度。现在旋转180度,X轴上的旋转是负的。当鼠标向上移动时,球体向下旋转。

如何解决这样的问题?也许我在别的地方做错了,可能会弄乱四元数?

也许我应该提到,在playercontroller(pl.js)中,我将旋转应用于sphereBody,而不是yaw-和pitchObjects。

pl.js相关代码(第49行):
var onMouseMove = function ( event ) {
    if ( scope.enabled === false ) return;
    var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
    var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;

    cannonBody.rotation.y -= movementX * 0.002;
    cannonBody.rotation.x -= movementY * 0.002;
    cannonBody.rotation.x = Math.max( - PI_2, Math.min( PI_2, cannonBody.rotation.x ) );


    //console.log(cannonBody.rotation);
};

And(第174行):

    euler.x = cannonBody.rotation.x;
    euler.y = cannonBody.rotation.y;
    euler.order = "XYZ";
    quat.setFromEuler(euler);
    inputVelocity.applyQuaternion(quat);
    cannonBody.quaternion.copy(quat);
    velocity.x = inputVelocity.x;
    velocity.z = inputVelocity.z;

在animate()函数中,codependency(第305行):testballMesh.position.copy(sphereBody.position); testballMesh.quaternion.copy(sphereBody.quaternion);

问题是你给四元数分配角度的方式。四元数x,y,z,w属性与角度不直接兼容,因此需要进行转换。

这是如何设置大炮围绕给定轴的角度。四元数:

var axis = new CANNON.Vec3(1,0,0);
var angle = Math.PI / 3;
body.quaternion.setFromAxisAngle(axis, angle);

从四元数中提取欧拉角可能不是解决问题第二部分的最佳方法。当用户移动鼠标时,你可以只存储X轴和Y轴的旋转:

// Declare variables outside the mouse handler
var angleX=0, angleY=0;
// Inside the handler:
angleY -= movementX * 0.002;
angleX -= movementY * 0.002;
angleX = Math.max( - PI_2, Math.min( PI_2, angleX ) );

然后将旋转作为四元数,分别使用两个四元数(一个用于X角,一个用于Y角),然后将它们组合为一个:

var quatX = new CANNON.Quaternion();
var quatY = new CANNON.Quaternion();
quatX.setFromAxisAngle(new CANNON.Vec3(1,0,0), angleX);
quatY.setFromAxisAngle(new CANNON.Vec3(0,1,0), angleY);
var quaternion = quatY.mult(quatX);
quaternion.normalize();

将四元数应用于速度矢量:

var rotatedVelocity = quaternion.vmult(inputVelocity);

专业提示:如果可以避免,不要使用欧拉角。