2012-09-16 62 views
2

我想在LibGDX中居中一个256px x 256px图像。当我运行我使用的代码时,会在窗口的右上角渲染图像。对于相机的高度和宽度,我使用Gdx.graphics.getHeight();Gdx.graphcis.getWidth();。我将相机的位置设置为相机的宽度除以二和高度除以二...这应该把它放在屏幕的中间右边?当我绘制纹理时,我将它定位在摄像机的宽度和高度除以2的位置 - 所以它居中..或者我想。为什么图像没有画在屏幕的中心,有没有我不理解的东西?居中一个纹理LibGDX

谢谢!

+0

如果可能的话,请张贴一些代码和你做的截图。 – wanting252

回答

9

听起来好像你的相机是确定的。 如果您设置了纹理位置,您可以设置该纹理左下角的位置。它不居中。因此,如果将其设置为屏幕中心的坐标,则其延伸将覆盖该点右侧和顶部的空间。要将它居中,需要从x中减去一半的纹理宽度,并从y坐标中减去一半的纹理高度。沿着这些线:

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

您应该在摄像机的位置画出你的纹理 - 纹理的一半尺寸...

例如:

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, height/2, 0); 
     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(); 
    } 
} 
+0

即使用户调整游戏窗口大小,此方法也能正常工作 – Aerthel