2012-09-26 43 views
3

我試圖讓OrthographicCamera跟隨用戶控制的精靈。我無法讓相機正確更新位置。與其他人所做的相比,我看不出我的代碼出了什麼問題。使用Libgdx更新相機位置

我仍在學習,在這一點上,我會認爲問題是由一些簡單的事情引起的,我現在還不完全明白。

任何幫助表示讚賞,謝謝。

這是我的渲染器:

public class WorldRenderer { 

private static final float CAMERA_WIDTH = 10; 
private static final float CAMERA_HEIGHT = 7; 

private World world; 
private OrthographicCamera oCam; 
private Hero hero; 
ShapeRenderer debugRenderer = new ShapeRenderer(); 

/** TEXTURES **/ 
private Texture heroTexture; 
private Texture tileTexture; 

private SpriteBatch spriteBatch; 
private int width, height; 
private float ppuX; // Pixels per unit on the X axis 
private float ppuY; // Pixels per unit on the Y axis 

public void setSize (int w, int h) { 
    this.width = w; 
    this.height = h; 
    ppuX = (float)width/CAMERA_WIDTH; 
    ppuY = (float)height/CAMERA_HEIGHT; 
} 

public WorldRenderer(World world, boolean debug) { 
    hero = world.getHero(); 
    this.world = world; 
    spriteBatch = new SpriteBatch();   
    oCam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); 
    oCam.update(); 
    loadTextures(); 
} 


private void loadTextures() { 
    tileTexture = new Texture(Gdx.files.internal("images/tile.png")); 
    heroTexture = new Texture(Gdx.files.internal("images/hero_01.png")); 
} 

public void render() { 
    oCam.update(); 
    spriteBatch.begin(); 
    spriteBatch.disableBlending(); 
    drawTiles(); 
    spriteBatch.enableBlending(); 
    drawHero(); 
    spriteBatch.end(); 
} 

private void drawHero() { 
    spriteBatch.draw(heroTexture, hero.getPosition().x * ppuX, hero.getPosition().y * ppuY, Hero.SIZE * ppuX, Hero.SIZE * ppuY); 
    oCam.position.set(hero.getPosition().x, hero.getPosition().y, 0); 
} 
} 

回答

4

SpriteBatch管理自己的投影和變換矩陣。所以,你必須設置它的矩陣(如果可能的話,在調用begin()之前)。除非需要單獨訪問矩陣(投影和模型視圖,例如在着色器中),否則將投影矩陣設置爲投影模型視圖矩陣就足夠了。

無論如何,這應該在你的代碼工作:

oCam.update(); 
spriteBatch.setProjectionMatrix(oCam.combined); 
+0

它工作!非常感謝你,清除我所有的問題! – Zifendale

1

試試你的oCam.update();

更新後調用oCam.apply(Gdx.gl10);()只做計算,但你永遠不會應用它們。

+0

我試過了一下,但無法讓它工作。使用'oCam.apply(Gdx.gl10);'導致我的程序在應用程序行中出現NullPointerException,當我嘗試編譯時。 – Zifendale

+0

你使用gl20嗎? – idanakav

0

關於idaNakav的回答,我不能看到這個時在LibGDX相機的應用功能了,萬一別人絆倒!所以現在我想像update()應該足夠了。

我的問題有點不同,我試圖把我的相機放在某些位置/用透視相機觀看,並且必須兩次動作才能工作。

我打電話:

camera.lookAt(xyz), camera.position.set(xyz), camera.up.set(xyz) 

第一個電話作出的相機更新的非常奇怪的變換。我應該一直在做:

camera.position.set(xyz), camera.lookAt(xyz), camera.up.set(xyz)