Vas
Vas

Reputation: 2064

Strange scaling in Libgdx

I'm trying to stretch a sprite to screen bounds uniformly. First I set the origin of the sprite to the centre of the screen. Since it's an Android device, I have several pages to scroll through to reach the end. In my experience, width*2 covers the extra distance.

mSprite.setOrigin(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()/2);
//these return 1080 and 960 on my device

Next I set the sprite's X and Y relative to the origin:

mSprite.setPosition(mSprite.getOriginX()-mSprite.getWidth()/2, mSprite.getOriginY()-mSprite.getHeight()/2);
//sprite width and height are 1440 and 1280

Now draw it with mSprite.draw(batch)

leftright

To a naked eye, it doesn't look off. Having measured the distance, there is no difference.

Now I apply a scale:

mSprite.setScale(1.2f, 1.2f);

Result:

leftright

As you can see, after scaling, the sprite no longer appears to be in the centre.

Why? What am I doing wrong? If this is how it's supposed to work, can anyone please recommend a viable workaround to uniformly scale a sprite?

Thanks

Upvotes: 1

Views: 626

Answers (1)

Justas Sakalauskas
Justas Sakalauskas

Reputation: 634

Instead of using the whole screen coordinates to set the origin of the sprite you should use sprites width and height:

mSprite.setOrigin(mSprite.getWidth()/2f, mSprite.getHeight()/2f);

Sprites use separate coordinate system that has (0,0) at the bottom left corner of the sprite .

Since sprite's origin doesn't effect the way you set your position ( It will always be in bottom left corner)

Set position to the middle:

mSprite.setPosition(screenWidth/2f-mSprite.getWidth/2f,screenHeight/2f - mSprite.getHeight/2f);

This also assumes that your camera is at position (screenWidth/2f,screenHeight/2f).

If your camera isn't looking at (screenWidth/2f,screenHeight/2f) and instead is positioned at (0,0) then set sprite's position like this:

mSprite.setPosition(-mSprite.getWidth/2f, - mSprite.getHeight/2f);

Upvotes: 2

Related Questions