LibGDX - 试图为精灵制作动画,让整个游戏崩溃

时间:2014-12-15 23:40:46

标签: java android animation libgdx 2d

我正在开发Android游戏,到目前为止我绘制游戏对象的方式是我在游戏中初始化它们然后将它们放入 GameObject的数组列表中 (每个对象都扩展了这个抽象类;播放器,标志,硬币)。此数组列表将传递到渲染器,然后使用for循环(遍历数组列表)绘制对象。

我正在尝试添加一个名为Coin的新 GameObject 。与其他对象不同,我希望这个对象是动画的,并且已经有8张图片代表动画的每一帧。这是我的代码(使用libgdx Animation类):

public class Coin extends GameObject implements Screen {
private SpriteBatch batch;
private Animation animation;
private float time;

public Coin(Sprite spr, float xPos, float yPos,
        float radius) {
    super(spr, xPos, yPos, radius);
    setxPos(xPos);
    setyPos(yPos);
    batch = new SpriteBatch();
    time = 0;
}

public void render(float delta) {
// TODO Auto-generated method stub
batch.begin();
batch.draw(animation.getKeyFrame(time += delta), getxPos(), getyPos());
batch.end();
}


@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub

}

@Override
public void show() {
    // TODO Auto-generated method stub
    //batch = new SpriteBatch();
    animation = new Animation(1 / 3f, 
            new TextureRegion(new Texture("coin1.png")), 
            new TextureRegion(new Texture("coin2.png")),
            new TextureRegion(new Texture("coin3.png")), 
            new TextureRegion(new Texture("coin4.png")), 
            new TextureRegion(new Texture("coin5.png")), 
            new TextureRegion(new Texture("coin6.png")), 
            new TextureRegion(new Texture("coin7.png")), 
            new TextureRegion(new Texture("coin8.png")));
    animation.setPlayMode(Animation.PlayMode.LOOP);
}
@Override
public void hide() {
    // TODO Auto-generated method stub

}

@Override
public void pause() {
    // TODO Auto-generated method stub

}

@Override
public void resume() {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {
    // TODO Auto-generated method stub
    batch.dispose();
}

}

我从LogCAT得到的错误是NullPointerException @ batch.draw(animation.getKeyFrame(time + = delta),getxPos(),getyPos());

有谁知道如何解决这个问题?任何见解都将受到高度赞赏

1 个答案:

答案 0 :(得分:0)

编写此代码:

public Coin(Sprite spr, float xPos, float yPos,
    float radius) {
super(spr, xPos, yPos, radius);
setxPos(xPos);
setyPos(yPos);
batch = new SpriteBatch();
time = 0;
loadAnimation();
}




 public void loadAnimation() {
    // TODO Auto-generated method stub
    //batch = new SpriteBatch();
    animation = new Animation(1 / 3f, 
            new TextureRegion(new Texture("coin1.png")), 
            new TextureRegion(new Texture("coin2.png")),
            new TextureRegion(new Texture("coin3.png")), 
            new TextureRegion(new Texture("coin4.png")), 
            new TextureRegion(new Texture("coin5.png")), 
            new TextureRegion(new Texture("coin6.png")), 
            new TextureRegion(new Texture("coin7.png")), 
            new TextureRegion(new Texture("coin8.png")));
    animation.setPlayMode(Animation.PlayMode.LOOP);
}