0
我試圖實現一個相機類。其中一種模式應該是基本的FPS攝像機行爲,當您可以使用鼠標改變方向時,向左/向右移動並相對於向前/向上方向前後移動。我有以下代碼,它似乎在開始時工作正常,但然後方向向量被損壞:FPS相機執行錯誤(OpenGL/GLUT/C++)
我的想法是,我不存儲當前方向的角度,但旋轉向前矢量(我已經有)通過每個像素1-2度上glutPassiveMotionFunc()
:
void Camera::Control(int x, int y)
{
switch (mode) {
case AVATAR:
if (x < prevX) direction.Rotate(1. * (prevX - x), up.Inverted());
if (x > prevX) direction.Rotate(1. * (x - prevX), up);
if (y < prevY) direction.Rotate(1. * (prevY - y), direction % up);
if (y > prevY) direction.Rotate(1. * (y - prevY), up % direction);
direction.Normalize();
//up = (direction % up) % direction; //UP in vitual space or for the camera?
prevX = x;
prevY = y;
//Debug vector values:
//printf("\nwinX: %d\twinY: %d\n", x, y);
//printf("radX: %0.3f\tradY: %0.3f\n", x, y);
//printf("dirX: %0.3f\ndirY: %0.3f\ndirZ: %0.3f\n", direction.X, direction.Y, direction.Z);
//printf("posX: %0.3f\nposY: %0.3f\nposZ: %0.3f\n", position.X, position.Y, position.Z);
break;
case ORBIT: /* ... */ break;
default: break;
}
}
掃射工作良好:
void Camera::Control(int key)
{
switch (key) {
case 'w': position += direction.Normal(); break;
case 's': position -= direction.Normal(); break;
case 'a': position += (up % direction).Normal(); break;
case 'd': position += (direction % up).Normal(); break;
default: break;
}
}
相機如何刷新其視圖:
void Camera::Draw()
{
gluLookAt(position.X, position.Y, position.Z, position.X + direction.X, position.Y + direction.Y, position.Z + direction.Z, up.X, up.Y, up.Z);
}
矢量的旋轉:
void Vector::Rotate(float angle, float x, float y, float z)
{
float rad = angle * PI/180.;
float s = sin(rad), c = cos(rad);
float matrix[9] = {
x*x*(1-c)+c, y*x*(1-c)-s*z, z*x*(1-c)+s*y,
x*y*(1-c)+s*z, y*y*(1-c)+c, z*y*(1-c)+s*x,
x*z*(1-c)-s*y, y*z*(1-c)+s*x, z*z*(1-c)+c
};
*this = Vector(X * matrix[0] + Y * matrix[3] + Z * matrix[6], X * matrix[1] + Y * matrix[4] + Z * matrix[7], X * matrix[2] + Y * matrix[5] + Z * matrix[8]);
}
void Vector::Rotate(float angle, Vector& axis)
{
Rotate(angle, axis.X, axis.Y, axis.Z);
}
當我測試的旋轉FUNC而且整個概念只在X軸上旋轉,它工作得很好。我可以環顧UP(0, 1, 0)
矢量(Y軸)。僅在(方向%上)和(上方%方向)旋轉也可以。 (Vector::operator%(Vector& other)
定義了交叉乘積。)當我計算X和Y位置的旋轉時會出現問題。有任何想法嗎?
你能舉一些錯誤的行爲的例子嗎? – hivert