【问题标题】:FPS camera implementation error (OpenGL/GLUT/C++)FPS 相机实现错误(OpenGL/GLUT/C++)
【发布时间】:2014-03-22 15:16:40
【问题描述】:

我尝试实现一个相机类。它的一种模式应该是基本的 FPS 相机行为,当您可以使用鼠标改变方向时,与向前/向上方向相比,左右移动和向前向后移动。我有以下代码,一开始似乎可以正常工作,但随后方向向量被破坏:

我的想法是我不存储当前方向的角度,而是在glutPassiveMotionFunc() 上将前向矢量(我已经拥有)每像素旋转 1-2 度:

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);
}


当我测试旋转功能并且整个概念仅围绕 X 轴旋转时,它运行良好。我可以环顾UP(0, 1, 0) 向量(Y 轴)。仅围绕(方向 % 向上)和(向上 % 方向)旋转也可以。 (Vector::operator%(Vector&amp; other) 定义叉积。)当我计算 X 和 Y 位置的旋转时会出现问题。有什么想法吗?

【问题讨论】:

  • 你能举一个错误行为的例子吗?

标签: c++ opengl camera rotation glut


【解决方案1】:

在应用 Y 旋转之前计算方向 % 并标准化结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多