Move a camera view with arrow keys

How can i move a camera view using arrow keys, in the program i have a cube

Ok, please keep in mind that the example I’m going to show you is based on modern OpenGL, not 1.x style OpenGL. Generally, if you’re sending vertices one by one with glVertex4f, glNormal3f, glTexCoord2f and using glPushMatrix() and glPopMatrix(), or using OpenGL’s built in lighting, then you’re using OpenGL 1.x style code. Unfortunately a lot of tutorials still use this style.

Assuming you’re trying for a free camera that’s not locked onto the cube, your camera should have some basic properties like: Position, field of view, near plane, far plane, forward vector (likely you would calculate this from an x, y, z rotation value), up vector (this can just be a unit Y-axis vector if your camera doesn’t need to do a barrel roll).

You need to calculate two matrices from your camera (don’t forget to convert angles to radians first):

  1. Projection Matrix: You build this based on your screen aspect ratio, field of view, near plane and far plane like: glm::perspective(fieldOfView, (float)windowWidth / (float)windowHeight, nearPlane, farPlane);
  2. View matrix: Built based on your camera parameters, like: glm::lookAt(cameraPosition, cameraPosition + cameraForwardVector, cameraUpVector). Or, if you want to point it at a specific object, just change the second parameter to the target position.

Assuming your cube is at (0, 0, 0), you probably want your camera to start at something like (0, 0, -6) with its direction facing down the positive Z axis (i.e. looking forward into the scene). From there, you can adjust the camera’s position and rotation based on your keyboard input. If you want to do it quick and dirty, you could just try adjusting the position of the camera and don’t worry about rotation just yet.

Each frame you just recalculate the view matrix from the camera’s latest position, rotation, etc. The projection matrix can be calculated at load time and reused as long as you don’t plan on changing the screen resolution, FOV angle or near/far planes.