居中一个纹理 LibGDX

4
我正在尝试在LibGDX中将一个256像素X 256像素的图像居中。当我运行使用的代码时,它会将图像呈现在窗口的右上角。对于相机的高度和宽度,我使用Gdx.graphics.getHeight();Gdx.graphcis.getWidth();。我将相机的位置设置为相机宽度除以二和高度除以二...这应该把它放在屏幕中间,对吗?当我绘制纹理时,我将其位置设置为相机宽度和高度除以二--所以它是居中的..或者我认为是这样。为什么图像没有绘制在屏幕中央,有什么我没有理解的地方吗?

谢谢!


如果可能的话,请发布一些代码和您所做的屏幕截图。 - wanting252
2个回答

13

看起来你的相机没问题。 如果你设置纹理的位置,你会设置该纹理左下角的位置。它不是居中的。因此,如果将其设置为屏幕中心点的坐标,则其范围将覆盖该点右侧和顶部的空间。要使其居中,您需要从x坐标减去纹理宽度的一半,并从y坐标减去纹理高度的一半。可以类似以下方式实现:

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

6
您应该在相机位置绘制纹理-纹理尺寸的一半...例如:
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();
    }
}

即使用户调整游戏窗口的大小,该方法仍然可以正常工作。 - Aerthel
运行得非常好!你可能刚刚拯救了我的项目:D - JPadley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接