Mat*_*man 5 quaternions game-physics
我有一个沿速度矢量移动的射弹物体.我需要确保物体始终面向速度矢量的方向.此外,我使用四元数而不是矩阵表示对象旋转.
我知道第一步是找到一个正交基础:
forward = direction of velocity vector
up = vector.new(0, 1, 0)
right = cross(up, forward)
up = cross(forward, right)
Run Code Online (Sandbox Code Playgroud)
我如何将基础转换为旋转四元数?
解
请注意,我想赞扬Noel Hughes提供的答案,但我想用自己的经验来澄清.伪代码如下:
vec3 vel = direction of velocity vector
vec3 forward = (1, 0, 0) // Depends on direction your model faces. See below.
vec3 axis = cross(forward, vel)
if (axis == 0) then quit // Already facing the right direction!
axis = normalize(axis)
float theta = acos(vel.x/sqrt(vel.x^2, vel.y^2, vel.z^2))
quat result = (0, axis.y * sin(theta/2), axis.z * sin(theta/2), cos(theta/2)
Run Code Online (Sandbox Code Playgroud)
四元数的最后一个元素是标量部分,前三个元素是虚部.此外,上面的伪代码假定您在"模型空间"中的对象指向正x轴.在我的例子中,对象实际上指向正y轴,在这种情况下我做了以下更改:
vec3 vel = direction of velocity vector
vec3 forward = (0, 1, 0) // Note that y-component is now 1
vec3 axis = cross(forward, vel)
if (axis == 0) then quit
axis = normalize(axis)
float theta = acos(vel.x/sqrt(vel.x^2, vel.y^2, vel.z^2))
quat result = (axis.x * sin(theta/2), 0, axis.z * sin(theta/2), cos(theta/2)
// Note that SECOND component above is now 0
Run Code Online (Sandbox Code Playgroud)
小智 4
我假设您不关心射弹的方向,除了纵轴与速度矢量对齐,并且纵轴是 (1, 0, 0) 的 x 轴。
你走在正确的轨道上。归一化速度向量,(vx, vy, vz)/sqrt(vx^2 + vy^2 + vz^2) 与其穿过x轴并归一化结果 - (0, yn, zn) - 这就是旋转四元数的轴。旋转角度就是 theta = vx/sqrt(vx^2 + vy^2 + vz^2) 的反余弦。所得四元数为
(0, yn, zn)sn(theta/2) cos(theta/2)