2
votes

I have a "camera" in my opengl program that I recently finished. However, I've noticed that whenever I rotate and then move again, the x, y, and z angles change. For example, when I press the "w" key, I move forward along the "z" axis. If I then rotate the camera 90 degrees, when I push the "W" key, I will actually be moving right, seemingly along the "x" axis. It makes sense why this happens, I'm just wondering why its happening. Here's the rotation function:

private void camera() {
    glRotatef(xrot, 1.0f, 0.0f, 0.0f);
    glRotatef(yrot, 0.0f, 1.0f, 0.0f);
}

The keyboard function:

if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        xpos -= 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        xpos += 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
        zpos += 0.03f * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
        zpos -= 0.035 * delta;
    }
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
        xrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
        xrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
        yrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
        yrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }

    }

And my translate function:

        glTranslated(xpos, ypos, zpos - 30);

any ideas on how to solve this?

2

2 Answers

0
votes

maybe look at camera based on old gluLookAt, then you will have better control over the camera position and where it is pointing.

here are some links:

2
votes

You probably expect to move in reference to where your camera is pointing. That means adding deltas to both x,y and z position when applicable.

Luckily when you have computed your cameras viewMatrix from euler angles (xrot, yrot), the rotation matrix contains exactly the values to add:

 [rx ux fx - ]
 [ry uy fy - ] = viewMatrix
 [rz uz fz - ]
 [ - -  -  - ]

Ignoring the elements marked with '-', you should add/subtract the "right" column vector = (rx,ry,rz) when moving right/left, the "up" vector = (ux,uy,uz) when moving up/down and front vector (fx,fy,fz) when moving front/back.

If altitude remains unchanged, then just ignore ry,uy,fy components but prepare to normalize the two remaining component.