Skip to content

Instantly share code, notes, and snippets.

@half2me
Created November 25, 2016 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save half2me/011b19f6bfd73b2ec39d14c1934b18a6 to your computer and use it in GitHub Desktop.
Save half2me/011b19f6bfd73b2ec39d14c1934b18a6 to your computer and use it in GitHub Desktop.
OpenGL Camera rotation problem
class Camera {
public:
vec4 eye; // Specifies the position of the eye point.
vec4 center; // Specifies the position of the reference point.
vec4 up; // For tilting the camera
float fov; // Field of view
float near, far; // Near and far clipping plane
Camera() {
eye = vec4(0, 0, 2);
center = vec4();
up = vec4(0, 1, 0);
fov = 45 * DEG2RAD;
far = 100.0f;
near = 0.1f;
}
mat4 V() { // View matrix glm::lookAt(eye, center, up)
vec4 Z = (eye - center).normal();
vec4 X = up % Z;
vec4 Y = Z % X;
return mat4(
X.x(), Y.x(), Z.x(), 0.0f, // @ @
X.y(), Y.y(), Z.y(), 0.0f, // @ Rotation @
X.z(), Y.z(), Z.z(), 0.0f, // @ @
X * eye, Y * eye, Z * eye, 1.0f // Translation
);
}
mat4 P() { return Pers(); }
mat4 Pers() { // Perspective Projection matrix
float Q = far / (far - near);
return mat4(1 / tanf(fov / 2), 0, 0, 0,
0, 1 / tanf(fov / 2), 0, 0,
0, 0, Q, 1,
0, 0, -Q * near, 1);
}
mat4 Portho() { // Orthogonal Projection matrix
return mat4(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1 / far, 0,
0, 0, -(near + 1), 1
);
}
};
void onKeyboard(unsigned char key, int pX, int pY) {
printf("Eye: %0.2f, %0.2f, %0.2f\n", camera.eye[0], camera.eye[1], camera.eye[2]);
float theta = 2 * DEG2RAD;
switch (key) {
case 'q':
exit(0);
case 'a':
camera.eye = camera.eye * mat4(
cosf(theta), 0, -sinf(theta), 0,
0, 1, 0, 0,
sinf(theta), 0, cosf(theta), 0,
0, 0, 0, 1
);
break;
case 'd':
camera.eye = camera.eye * mat4(
cosf(-theta), 0, -sinf(-theta), 0,
0, 1, 0, 0,
sinf(-theta), 0, cosf(-theta), 0,
0, 0, 0, 1
);
break;
case 'w':
camera.eye = camera.eye * mat4(
1, 0, 0, 0,
0, cosf(theta), sinf(theta), 0,
0, -sinf(theta), cosf(theta), 0,
0, 0, 0, 1
);
break;
case 's':
camera.eye = camera.eye * mat4(
1, 0, 0, 0,
0, cosf(-theta), sinf(-theta), 0,
0, -sinf(-theta), cosf(-theta), 0,
0, 0, 0, 1
);
break;
default:
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment