Making the Camera

Okay, before you start making a camera class, let's go over what it needs to do first.

A 2D Camera needs to:

  • move the origin to see the game world
  • keep track of the player object's position

The first part we already have a pretty good idea of how to do. We can use translate() to move the origin around, but making an object that just translates could be a little tricky. Remember the push() and pop() functions? The canvas could get messy really fast if you don't revert the matrix when the camera is done, so you'll need those too. Because it would be hard to import the draw loop into a camera object, we'll need separate functions for when the camera transformation begins and ends.

With that in mind, the first task breaks down even further

  • move the origin to see the game world
  • save the origin position using push()
  • translate() the origin based on a given value
  • revert the origin back to its default position using pop()

This means that you'll need to make a function where the transformation value updates.

Based on these requirements, we can begin to ouline a class that looks like this:

class Camera
{
    constructor(){}
    update(){}
    begin(){}
    end(){}
}

The constructor() and the update() functions can be made later when you start making the camera follow the player. For now, you just need to add push() and translate() to the begin() function, and put a translation value in the constructor. At this point, the value that you pass it is arbitrary, since you'll relate it to the player object's position later.

class Camera
{
    constructor()
    {
        this.translation = createVector(0, 0);
    }
    update(){}
    begin()
    {
        push()
        translate(this.translation.x, this.translation.y)
    }
    end()
    {
        pop()
    }
}

Now that you have your camera class started, let's make an instance of it in our game. First, we make a variable for our camera with let cam;, then we call it's constructor in the setup loop with cam = new Camera().

Finally, you can add the cam.begin() and cam.end() functions before and after drawing the other objects in our scene.

Try playing around with the x value of the camera's this.translation property and see how the canvas changes. If you're feeling fancy, why not try sin(frameCount) to animate the translation?

When you're ready to move on, we can add the player-following behavior to the camera.