使用OpenGL进行FPS相机旋转

时间:2013-09-26 14:42:56

标签: java opengl camera lwjgl frame-rate

我试图让它像FPS风格的相机,你可以用鼠标环顾四周。我已经有了它的工作但是当我四处移动然后水平看时,它会从原始点旋转所有东西。我做错了什么?

private float moveSpeed = 0.1f;

private Vector3f camera;

private float horizontalAngle = 0.0f;
private float verticleAngle = 0.0f;

public Game() {
    Mouse.setGrabbed(true);
    camera = new Vector3f(0.0f, 0.0f, 0.0f);
}

public void input(){
    horizontalAngle += Mouse.getDX() * 0.05f;
    verticleAngle += -Mouse.getDY() * 0.05f;

    if(Keyboard.isKeyDown(Keyboard.KEY_W)){
        camera.x -= moveSpeed * Math.sin(Math.toRadians(horizontalAngle));
        camera.z += moveSpeed * Math.cos(Math.toRadians(horizontalAngle));
    }
    if(Keyboard.isKeyDown(Keyboard.KEY_S)){
        camera.x += moveSpeed * Math.sin(Math.toRadians(horizontalAngle));
        camera.z -= moveSpeed * Math.cos(Math.toRadians(horizontalAngle));
    }
    if(Keyboard.isKeyDown(Keyboard.KEY_A)){
        camera.x -= moveSpeed * Math.sin(Math.toRadians(horizontalAngle - 90));
        camera.z += moveSpeed * Math.cos(Math.toRadians(horizontalAngle - 90));
    }
    if(Keyboard.isKeyDown(Keyboard.KEY_D)){
        camera.x -= moveSpeed * Math.sin(Math.toRadians(horizontalAngle + 90));
        camera.z += moveSpeed * Math.cos(Math.toRadians(horizontalAngle + 90));
    }

    if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)){
        Mouse.setGrabbed(false);
    }
}

public void update(){

}

public void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // draw quad

    glTranslatef(camera.x, camera.y, camera.z);
    glRotatef(verticleAngle, 1.0f, 0.0f, 0.0f);
    glRotatef(horizontalAngle, 0.0f, 1.0f, 0.0f);


    glBegin(GL_QUADS);

    glColor3f(1.0f, 0.5f, 0.5f);
    glVertex3f(0.0f, 0.0f, -5.0f);
    glVertex3f(1.0f, 0.0f, -5.0f);
    glVertex3f(1.0f, 1.0f, -5.0f);
    glVertex3f(0.0f, 1.0f, -5.0f);

    glEnd();


    glRotatef(-horizontalAngle, 0.0f, 1.0f, 0.0f);
    glRotatef(-verticleAngle, 1.0f, 0.0f, 0.0f);
    glTranslatef(-camera.x, -camera.y, -camera.z);

    Display.sync(60);
    Display.update();
}

我正在使用带有Java的LWJGL。

1 个答案:

答案 0 :(得分:3)

您需要两个矢量来进行相机旋转:一个用于相机的位置(u),另一个用于相机的方向(v)(v的长度无关紧要)。然后使用gluLookAt(u.x, u.y, u.z, u.x+v.x, u.y+v.y, u.z+v.z, 0.0, 1.0, 0.0),意味着摄像机位于u位置,查看u + v点,向上方向的矢量为(0,1,0)。