Centering a texture LibGDX

11,087

Solution 1

It sounds as if your camera is ok. If you set the textures position, you set the position of the lower left corner of that texture. It is not centered. Therefore if you set it to the coordinates of the center of the screen, its extends will cover the space to the right and the top of that point. To center it, you need to subtract half of the textures width from the x, and half of the textures height from the y coordinate. Something along these lines:

image.setPosition(Gdx.graphics.getWidth()/2 - image.getWidth()/2, 
Gdx.graphics.getHeight()/2 - image.getHeight()/2);

Solution 2

You should draw your texture at the camera position - half the dimensions of the texture...

For example:

class PartialGame extends Game {
    int w = 0;
    int h = 0;
    int tw = 0;
    int th = 0;
    OrthographicCamera camera = null;
    Texture texture = null;
    SpriteBatch batch = null;

    public void create() {
        w = Gdx.graphics.getWidth();
        h = Gdx.graphics.getheight();
        camera = new OrthographicCamera(w, h);
        camera.position.set(w / 2, h / 2, 0); // Change the height --> h
        camera.update();
        texture = new Texture(Gdx.files.internal("data/texture.png"));
        tw = texture.getwidth();
        th = texture.getHeight();
        batch = new SpriteBatch();
    }

    public void render() {
        batch.begin();
        batch.draw(texture, camera.position.x - (tw / 2), camera.position.y - (th / 2));
        batch.end();
    }
}
Share:
11,087
foobar5512
Author by

foobar5512

Updated on June 28, 2022

Comments

  • foobar5512
    foobar5512 almost 2 years

    I am trying to center a 256px X 256px image in LibGDX. When i run the code I'm using it renders the image in the upper right hand corner of the window. For the camera's height and width I use Gdx.graphics.getHeight(); and Gdx.graphcis.getWidth(); . I set the cameras position to the camera's width divided by the two and its height divided by two... this should put it in the middle of the screen right? when I draw the texture, I set it's position to the camera's width and height divided by two -- so it's centered..or so I think. Why doesn't the image draw in the center of the screen, is there something I'm not understanding?

    Thanks!

  • Aerthel
    Aerthel over 9 years
    This method works correctly even if the user resizes the game window
  • JPadley
    JPadley over 5 years
    Works like a charm! You've probably just saved my project :D