我使用来自IMU设备的输入来创建四元数(w,x,y,z)。然后我将四元数归一化,并根据此从四元数到欧拉角的转换代码找到欧拉角:
private PVector setEulerAngles(){
// roll: x-axis rotation
float sinr = 2.0f * (w*x + y*z);
float cosr = 1.0f - 2.0f * (x*x + y*y);
float roll = (float)Math.atan2(sinr, cosr);
// pitch: y-axis rotation
float sinp = 2.0f * (w*y - z*x);
float pitch = 0.0f;
if(Math.abs(sinp) >= 1){
pitch = (float)Math.copySign(Math.PI/2, sinp);
} else {
pitch = (float)Math.asin(sinp);
}
// yaw: z-axis rotation
float siny = 2.0f * (w*z + x*y);
float cosy = 1.0f - 2.0f * (y*y + z*z);
float yaw = (float)Math.atan2(siny, cosy);
return new PVector(roll, pitch, yaw);
}
然后我在“处理”中应用ZYX旋转。但是,要定向我的3D对象,我必须翻转z和y值,并抵消z旋转的y值。我还必须为rotateY创建偏移(PI / 2),因此我的对象面向正确的方向。对象绕着x和y轴完美地旋转,但是沿着z轴,对象沿正确的方向旋转,但是会突然翻转。是否有一种简单的解决方案来使对象绕z轴正确旋转?
pushMatrx();
translate(pos.x, pos.y, 0);
rotateZ(-q.eulerAngles.y);
rotateY(q.eulerAngles.z+(PI/2));
rotateX(q.eulerAngles.x);
shape(model);
popMatrix();