Libgdx相机和视口

时间:2018-09-07 18:54:51

标签: camera libgdx viewport

使用libgdx已有一段时间了。现在我有一个小问题。我需要我的相机跟随我的播放器。以前已经做过,但是现在我无法正常工作。

public class HungerGames extends ApplicationAdapter implements Screen, InputProcessor {
SpriteBatch batch;
Texture img, background;
Player player;
OrthographicCamera camera;
Viewport viewport;

@Override
public void create () {
    batch = new SpriteBatch();
    img = new Texture(Gdx.files.internal("player.png"));
    background = new Texture(Gdx.files.internal("background.jpg"));
    player = new Player(new Vector2(0,0), 100, img);
    camera = new OrthographicCamera();
    camera.setToOrtho(false);

    viewport = new ExtendViewport(800,600, camera);
    viewport.apply();
    Gdx.input.setInputProcessor(this);
}

@Override
public void render () {
    Gdx.gl.glClearColor(0,0,0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    updateControls();
    camera.position.set(player.getPosition().x, player.getPosition().y, 0);
    camera.update();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();

    batch.draw(background, 0,0);
    batch.draw(player.getSprite(), player.getPosition().x, player.getPosition().y);
    batch.end();
    System.out.println(camera.position + " " + player.getPosition());

}

所以这是重要的代码。如果我设置batch.setProjectionMatrix(camera.combined); ,整个屏幕为黑色。如果我取消注释,则背景和播放器将渲染,但相机不会跟随播放器。这也是继承Player的Entity类:

public class Entity{

Vector2 position;
float health;
Texture sprite;
SpriteBatch batch;

public Entity(Vector2 position, float health, Texture sprite) {
    this.position = position;
    this.health = health; 
    this.sprite = sprite;
}

public Vector2 getPosition() {
    return position;
}

public void setPosition(Vector2 position) {
    this.position = position;
}

public Texture getSprite() {
    return sprite;
}

public void setSprite(Texture sprite) {
    this.sprite = sprite;
}

public float getHealth() {
    return health;
}
public void setHealth(float health) {
    this.health = health;
}

public void moveX(float amount) {
    this.position.x = this.position.x + amount;
}

public void moveY(float amount) {
    this.position.y = this.position.y + amount;
}

public void update(float delta) {

}

}

我在这里错过了一些小事吗?我一直在谷歌搜索,但现在我真的不明白怎么了。好吧,在此先感谢:)

p.s

我还对凸轮坐标和播放器坐标进行了设置,它们是相同的:

(53.0,51.0,0.0)(53.0,51.0) (53.0,51.0,0.0)(53.0,51.0) (53.0,51.0,0.0)(53.0,51.0) (53.0,51.0,0.0)(53.0,51.0)

0 个答案:

没有答案