我有一个游戏,其中有一个0-360度的2D罗盘,可以告诉你摄像机所面对的角度,无论高度如何。
我试图弄清楚如何使用模型视图矩阵获得该角度。我的算法有效但不是100%的时间。
我有以下代码用于从模型视图矩阵中获取角度。
Vector3D<float> GetEulerAngles(float ModelView[16])
{
float X = atan2(ModelView[9], ModelView[10]) * (180 / PI);
float Y = atan2(-ModelView[8], sqrt(pow(ModelView[0], 2) + pow(ModelView[4], 2))) * (180 / PI);
float Z = atan2(ModelView[4], ModelView[0]) * (180 / PI);
return {X < 0 ? 360 - X : X, Y < 0 ? 360 - Y : Y, Z < 0 ? 360 - Z : Z};
}
/*
Works so long as the camera is at its highest point (looking down on the player - 66deg angle)
-------
OR any height and: 90 < CompassAngle < 360 is true.
*/
int GetCompassAngle()
{
glGetFloatv(GL_MODELVIEW_MATRIX, &ModelView[0]);
Vector3D<float> angles = GetEulerAngles(ModelView);
return round(to_degrees(Z));
}
/*
Works so long as the camera is at any height (and: 0 < CompassAngle < 90)
*/
int GetCompassAngle()
{
glGetFloatv(GL_MODELVIEW_MATRIX, &ModelView[0]);
Vector3D<float> angles = GetEulerAngles(ModelView);
return round(360 - to_degrees(Y));
}
当我放下相机时,第二个GetCompassAngle
正常工作。它从欧拉角读取“Y”。但是,如果摄像机位于最高点,它会从欧拉角读取“Z”。
这些工作但是当旋转和改变摄像机角度时会改变数值,有时它会给我错误的指南针角度。
如何以某种方式组合它们或者无论相机高度如何都能获得罗盘角度?
以下是一些数字,如果它有助于我的情况:
CompassHeight (Max - 65 deg from floor):
CompassDeg (X, Y, Z):
0deg: 65.0537253622628 358.814165052872 1.07537657735905
90deg: 88.1642315504792 312.258382165551 85.6596194029266
180deg: 115.286564608444 358.615368311296 178.747763300624
270deg: 90.1881102037367 47.9243745800853 269.562655218025
//Notice the "Z" values are the right compass angle or close enough.
CompassHeight (Low - 13 deg from floor):
CompassDeg (X, Y, Z):
0deg: 13.7624148875505 1.69169652884413 359.597596807979
90deg: 77.9527238194348 283.654247204305 77.5930785465022
180deg: 166.486754945655 355.694293448629 178.99462624173
270deg: 87.8507577921787 77.1021010565408 272.207848194156