Friday, March 25, 2016

c++ - Implementing a camera / viewport to a 2D game


What is the most practical way to implement camera/viewport to a 2D-game?



I've read, that I should store the object world position instead of position relative to the screen?


Current situation:


I have implemented a simple 2D-game where I load objects and levels from XML-files. Currently the level XML-file looks like this:






...



All objects have a 2d-vector "position" storing their current location on the screen.


What I want it to be:


Viewport/gameworld illustration


In the picture:



  • Camera is either 800x600 or 640x480

  • Blocks and sprites are 16x16 pixels.

  • World size may vary

  • The coordinates probably should be normalized relative to the world, not to the screen?

  • Viewport position relative to player's x, y and moves when the player reaches camera dead zone (similar to this video).



I'm asking pseudo examples / articles, but if you need to know what I'm using for the development: SDL & C/C++.



Answer



You need to have every object positioned relative to the world instead of the screen. Your camera should also have its own world coordinates so it can be drawn at a relative position in the world. It may also be convenient to have your camera follow an object, so wherever the object is, the camera just uses its coordinates. Typically the camera's coordinates will position it from the upper left corner. This means the camera would have a world position of approximately (0,24) in the picture.


As for actually drawing the objects the camera can "see", you must draw all objects relative to the camera's world coordinates. To compute an object's screen position relative to the camera, simply do:


int screenX, screenY; //screen position of the object being drawn

screenX = object.x-camera.x;
screenY = object.y-camera.y;


Obviously some objects are not actually visible to the camera, so you may want to implement a view culling system.


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...