Centering a texture LibGDX

ぐ巨炮叔叔 提交于 2019-12-12 13:22:12

问题


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!


回答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);



回答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();
    }
}


来源:https://stackoverflow.com/questions/12449229/centering-a-texture-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!