使用Libgdx更新相机位置

3

我正在尝试让一个OrthographicCamera跟随用户控制的精灵移动。但是我无法正确地更新相机的位置。与其他人所做的相比,我似乎看不出我的代码有什么问题。

我仍在学习过程中,我认为这个问题可能是由于某些简单的东西我目前还没有完全理解所导致的。

非常感谢任何帮助。

这是我的渲染器:

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);
 }
}
3个回答

4

SpriteBatch 管理其自己的投影和变换矩阵。因此,在调用 begin() 函数之前,您需要设置其矩阵(如果可能的话)。

除非您需要单独访问您的矩阵(例如在着色器中访问投影和模型视图矩阵),否则将投影矩阵设置为投影-模型-视图矩阵就足够了。

无论如何,以下代码应该可以正常工作:

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

1

尝试在oCam.update();之后调用oCam.apply(Gdx.gl10);

update()只进行计算,但你从未应用它们。


我尝试了一下,但无法使其正常工作。使用“oCam.apply(Gdx.gl10);”会导致我的程序在编译时在apply行处出现NullPointerException。 - Zifendale

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)

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