Using a camera in OpenGL

You'll learn now:

How can I use a camera in OpenGL?

First of all: There is no thing like a camera in OpenGL. But, of course, you can simulate one. All you need to know – and this is the same in reality: Moving an object is the same as moving yourself in the opposite direction. That means: If you want to simulate a viewer at the position (9|-3|10) you only have to apply the transformation glTranslate ( -9, 3, -10). It is the same with rotations. glScale is logically not used for camera simulation. That is all – nearly all.

You probably know games like Halflife, UnrealTournament and so on. They all have a "ghost mode". The user can move into all directions, look around and whatever he wants. What the user really does is to move (forwards or backwards) or rotate about a certain axis. So why not do this all with OpenGL commands? The problem is – again – that matrix operations must be swapped. So even if you don't use glLoadIdentity but the matrix stack, you couldn't apply a translation when the user wants to move forwards. What you could do would be to get the current matrix (there are OpenGL commands to do so), load the identity matrix, call your transformation command and then multiply the saved matrix with the modelview matrix. But there is another possibility, which I myself prefer: In C++ you create a camera class with methods like "move", "rotate" and so on. An object of this class would store the position and the direction that the "camera" looks to. If now "move" is called, you calculate the new view position using the direction. To apply the camera to your scene, you add a "render"-function to the class which calls the three "glRotate"s and a "glTranslate". I have used RotateX, RotateY and RotateZ. RotateY means you turn your head. Look out of the window instead of towards your monitor and you have done the same like RotateY. RotateZ means you look on the floor. RotateX isn't used too often. Mainly in racing games, when you're sitting in your car and the track is higher on the right than on the left, for example.

There is also another possibility to simulate a camera. GLU provides a function called gluLookAt. This is also a comfortable way, but it isn't too easy to get the "up-vector" without matrix calculations.

How can I get user input?

Using GLUT getting user input isn't difficult. You define a function that takes three arguments: an unsigned char for the key, and two integers for the mousepositon. To work with a mouse you should use other GLUT commands, but game programmers do use DirectInput anyway.

I'll use the keyboard method in the tutorials, because it's pretty easy to understand and the keyboard has enough keys to do a lot.

Here you can see the results of using this tutorial.

Back

**************************************************************************

Any comments? Conact me!

philipp.crocoll@web.de

www.codecolony.de