Implementing Camera Zoom in a 2D Engine

Posted by Luke on Game Development See other posts from Game Development or by Luke
Published on 2014-05-29T16:37:47Z Indexed on 2014/05/29 22:04 UTC
Read the original article Hit count: 182

Filed under:
|
|
|
|

I'm currently trying to implement camera scaling/zoom in my 2D Engine. Normally I calculate the Sprite's drawing size and position similar to this pseudo code:

render()
{
    var x = sprite.x;
    var y = sprite.y;
    var sizeX = sprite.width * sprite.scaleX; // width of the sprite on the screen
    var sizeY = sprite.height * sprite.scaleY; // height of the sprite on the screen
}

To implement the scaling i changed the code to this:

class Camera
{
    var scaleX;
    var scaleY;
    var zoom;
    var finalScaleX; // = scaleX * zoom
    var finalScaleY; // = scaleY * zoom
}

render()
{
    var x = sprite.x * Camera.finalScaleX;
    var y = sprite.y * Camera.finalScaleY;
    var sizeX = sprite.width * sprite.scaleX * Camera.finalScaleX;
    var sizeY = sprite.height * sprite.scaleY * Camera.finalScaleY;
}

The problem is that when the zoom is smaller than 1.0 all sprites are moved toward the top-left corner of the screen. This is expected when looking at the code but i want the camera to zoom on the center of the screen.

Any tips on how to do that are welcome. :)

© Game Development or respective owner

Related posts about 2d

Related posts about mathematics