2012-09-16 102 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