2D Camera

So lets say you're helping a friend make a 2D platformer game. They're a little new at this, so they're getting a bit stuck. They have a few things already made, like the player, the ground, the inputs, and they even imported Matter.js to take care of the physics.

The first thing we should do is take a look at their game and see how it's working. Try interacting with the game a bit, and read through the code that they've written. If you need to restart the game, try editing the code to refresh the canvas. If you feel like you've made a mistake in the code, you can also use command+Z or ctrl+Z to undo your changes.

Wait, what's Matter.js again?

If Matter.js is altogether alien to you, it might be worth opening up the documentation or looking through the examples. There's also a good tutorial series on The Coding Train on how to use Matter.js with p5. Your friend doesn't want to spend all day thinking about how to implement physics, so they just settled for using a physics library instead.

Arrow keys: Left / Right

Spacebar: Jump

The aesthetics of the game could use some polish, but your firend isn't really looking for feedback on that, and they can always improve that later anyway. You might have noticed a bigger problem with this game though: it's pretty small. Only the size of the game window, in fact.

"How do I make the level bigger?" your friend might ask. Well, we could simply add more elements outside of the canvas so the player box doesn't fall off into infinity, but that's not really what they're asking here, is it? Their real question is:

How might I see more of this world as the player moves around it?

Lets take a moment to reflect on this. In p5, everything is drawn in relation to the origin point (0,0). By default, this is in the top left of the canvas.

origin illustration here

This means, in order to see other parts of the game, we'll have to move the origin. What's more, we need to move the origin in relation to the player so that it stays on the screen. So in order to emulate a camera that is following the player along, we'll need to do both of these.

In Summary:

  • In order to see more of the game, we need to move the origin
  • In order to keep the player on the screen, we need to make the origin movements relational to the player object