Sunday, September 2, 2018

2d - How do I keep my character centred on screen?


I am making a game similar to Legend of Zelda: Link to the Past (top-down 2D action-adventure). I want the character to stay centred on the screen when he moves.


Currently, whenever the player wants to move, I move all of the map in the opposite direction. This works, but as I add more objects to the world, moving them all gets more complicated.


Is there a better way of approaching this?




Answer



The typical way of handling this is to create a camera object. The simplest form of a camera is just a position. This simple camera defines the "center" of the current view. So you don't modify all the positions of your tiles/entities, you just subtract the camera coordinates from the positions when drawing. In this situation, the camera does not "move".


While the camera and your character will share a position most of the time, you may still want to have them as separate values, so you can, for example, stop the camera from moving when it reaches the end of the world, but allow the player to continue moving.


A slightly more advanced camera does move. All entities and tiles are drawn without offset and the position from which you're rendering changes. This is very similar to the most basic camera, and you can still perform many of the same optimizations for selective rendering (only calling draw on what the camera can see), on both. It's essentially just a different way of thinking about it.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...