我有一个沿速度矢量移动的射弹物体。我需要确保对象始终面向速度矢量的方向。此外,我使用四元数而不是矩阵来表示对象旋转。
我知道第一步是找到一个正交基:
forward = direction of velocity vector
up = vector.new(0, 1, 0)
right = cross(up, forward)
up = cross(forward, right)
我如何将基础转换为旋转四元数?
解决方案
请注意,我想感谢 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)
四元数的最后一个元素是标量部分,前三个元素是虚部。此外,上面的伪代码假设您在“模型空间”中的对象指向正 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