好吧,我就是这样做的:
float xrot = 0;
float yrot = 0;
float zrot = 0;
Quaternion q = new Quaternion().fromRotationMatrix(player.model.getRotation());
if (q.getW() > 1) {
q.normalizeLocal();
}
float angle = (float) (2 * Math.acos(q.getW()));
double s = Math.sqrt(1-q.getW()*q.getW());
// test to avoid divide by zero, s is always positive due to sqrt
// if s close to zero then direction of axis not important
if (s < 0.001) {
// if it is important that axis is normalised then replace with x=1; y=z=0;
xrot = q.getXf();
yrot = q.getYf();
zrot = q.getZf();
// z = q.getZ();
} else {
xrot = (float) (q.getXf() / s); // normalise axis
yrot = (float) (q.getYf() / s);
zrot = (float) (q.getZf() / s);
}
但是当我尝试投入使用时,它似乎不起作用:
player.model.addTranslation(xrot * player.speed, 0, zrot * player.speed);
AddTranslation 需要 3 个数字来移动我的模型比许多空间 (x, y, z),但是当我给它上面的数字时它不会在它旋转的方向上移动模型(在 XZ 平面上) )
为什么这不起作用?
编辑:新代码,尽管现在大约偏离 45 度。
Vector3 move = new Vector3();
move = player.model.getRotation().applyPost(new Vector3(1,0,0), move);
move.multiplyLocal(-player.speed);
player.model.addTranslation(move);
最佳答案
xrot
、yrot
和 zrot
定义四元数指定的旋转轴。我认为您不想在 addTranslation()
调用中使用它们...一般来说,这与运动方向没有任何关系。
我的意思是:您的 3-D 物体——假设它是一架飞机——在其原始坐标中将有一个特定的首选运动方向 系统。因此,如果原始方向的质心位于原点,则 螺旋桨沿+X轴某处,飞机要向+X方向飞行。
现在您将引入一些坐标变换,将飞机旋转到其他方向。该旋转由旋转矩阵描述,或等效地由 四元数。旋转后飞机想朝哪个方向移动?
你可以找到 通过在 +X 方向取一个单位 vector :(1.0, 0.0, 0.0),然后应用 旋转矩阵或四元数到该 vector 以将其转换为新坐标 系统。 (然后按速度缩放它,就像你在上面所做的那样。)X、Y 和 Z 分量 变换后的缩放 vector 给出了沿每个轴的所需增量运动。转换后的 vector 通常不会成为四元数的旋转轴,我认为这可能是您的问题。
关于java - 四元数转角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4435199/