使纹理LibGDX居中

foo*_*512 3 android libgdx

我试图在LibGDX中居中256px X 256px图像.当我运行我正在使用它的代码时,会在窗口的右上角渲染图像.对于相机的高度和宽度,我使用Gdx.graphics.getHeight();Gdx.graphcis.getWidth();.我将摄像机的位置设置为摄像机的宽度除以2并将其高度除以2 ......这应该将它放在屏幕中间吗?当我绘制纹理时,我将它的位置设置为相机的宽度和高度除以2 - 所以它是居中的......所以我想.为什么图像不在屏幕中央绘制,有什么我不理解的东西?

谢谢!

小智 11

听起来好像你的相机还可以.如果设置纹理位置,则设置该纹理左下角的位置.它没有居中.因此,如果将其设置为屏幕中心的坐标,则其延伸将覆盖该点的右侧和顶部的空间.要使其居中,您需要从x中减去一半纹理宽度,并从y坐标中减去一半纹理高度.这些方面的东西:

image.setPosition(Gdx.graphics.getWidth()/2 - image.getWidth()/2, 
Gdx.graphics.getHeight()/2 - image.getHeight()/2);
Run Code Online (Sandbox Code Playgroud)


nEx*_*are 5

你应该在相机位置绘制纹理 - 纹理的一半尺寸......

例如:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)