A C++ Camera Class for Simple OpenGL FPS Controls

This is the third post of three, where we finally get to create a Camera class which encapsulates all the important properties of a camera suitable for FPS controls. I could, and indeed did, have this written to just use three floats for the camera position, three for the rotation, three for the movement speed etc – but it makes more sense to use a vector class to encapsulate those values into a single item and provide methods for easy manipulation, so that’s what I’ve done.

The end result of this is that although the Camera class now depends on the Vec3 class, the Camera class itself is now more concise and easier to use. If you don’t like the coupling you can easily break it and return to individual values, but I think I prefer it this way. Oh, and this class is designed to work with GLFW, although it could be very easily modified to remove that requirement and be used with SDL or something instead. In fact, we only ever use the glfwSetMousePos(x, y) method to reset the mouse position to the centre of the screen each frame!

Anyways, let’s look at the header first to see the properties and methods of the class:

Camera.h Header

Now for the implementation:

Camera.cpp Class

Rather than me explaining each individual piece of how to fit it together, here’s a worked example – it’s really quite easy to use:

Finally! Done! You can see a video of the first version of the FPS controls here – this code works identically, it’s just that the Camera is now in its own class, we’re using our own little Vec3 class to keep group and manipulate some values, and the whole thing works in a framerate independent manner thanks to the FpsManager class. Phew!


10 thoughts on “A C++ Camera Class for Simple OpenGL FPS Controls”

  1. Hello,
    I’ve tried converting your code to GLFW3, and I was able to make the mouse move, however, the WASD movement doesn’t work. I have the changes if you want I can e-mail them to you.

    1. I converted a project using the Camera class to GLFW3 the other day and ended up using this code:

      Somewhere in your setup code:

      Somewhere in the main.cpp file:

      Finally, somewhere in the Camera class:

  2. I realize this is an old post but I figured maybe someone will see this and get help from reading, but why are you handling the input in the Camera class. That totally gets in the way of almost anything you will need to do in the program later on. Make a seperate Input class and feed those values into the Camera class but handling it via the Camera class is absurd.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.