Viewing A Larger World

From CodeStuff
Jump to: navigation, search

In many games the screen represents a window into a much larger game area. As the player moves around you get to see more of the game world.

Mario.gif

Instead of the player moving across the world, the 'camera' stays focused on the player and the view of the entire world moves. So instead of the player moving to the right, everything else on the screen moves to the left. To do this is easier than it sounds.

Start with a simple example where we have a player that slowly moves out of view.


Running this program the player leaves the screen. but we have a function available to us called canvasTranslate(x,y). Imagine drawing an X on a piece of paper then moving the piece of paper and drawing another X. The new X is in a different position not because of the pen moving but the paper. That's what canvasTranslate does. It moves the drawing space itself.

What happens if we move the paper in the opposite direction to the player. The player is at x and increasing so we go
canvasTranslate(-player.x,0);
note the minus sign so we are moving the paper in the *other* direction. What happens if we place the canvasTranslate immediately before the drawPlayer?

That's the effect we were after, the player is standing still but it's also at the edge of the screen? Why is that? The player is drawn at player.x and the canvas is moved by -player.x which places the player at 0 onscreen. We'd rather the player stay in the center of the screen than at the edge, so we can take a bit off the amount we move back to place the player in the center.

canvasTranslate(320-player.x,0);
We can do the same for y as well. Halfway down the screen is 240 so lets make it
canvasTranslate(320-player.x,240-player.y);



Finally There's one last thing to fix. We print some text on the screen but as the player moves away we lose sight of the text. That's not very useful. The text is something we want to put on top, it's not really part of the game world so we don't want it to move around.

This is where the useful functions
canvasSave()
and
canvasRestore()
You can save and restore the state so you can jump back to before you started mucking around with positions.

This final program shows the canvas being saved before we draw the game world and restored afterwards so we can draw the text in the right place. It also tidies things up a little by moving all of the 'game world' drawing commands into their own function.