1
\$\begingroup\$

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

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

When your sprite is in the center of the screen its position should be unchanged by zooming. This tells me that if sprite.x is 0.5 the resulting x should still be 0.5 after the equation assuming that the center of the screen is 0.5.

This could achieve that:

var halfScreenWidth = Screen.width/2.0f;
var x = (sprite.x - halfScreenWidth) * Camera.finalScaleX + halfScreenWidth;
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .