要为您的敌人使用动画,您不需要创建敌人阵列,但需要
Animation
对象,就像您在问题的第一个代码段中所做的那样。
类似这样:
public void character() {
TextureRegion[] enemyAnimationTextures = new TextureRegion[] {new Texture("img1.png"), new Texture("img2.png"), new Texture("img3.png"), new Texture("img4.png")};
Animation<TextureRegion> animation = new Animation<>(0.15f, enemyAnimationTextures, PlayMode.LOOP); // use PlayMode.NORMAL if you don't want the animation to loop
enemy = new Enemy(animation);
}
现在,您需要能够绘制动画。因此,您需要添加一个将增量时间作为参数获取的绘制方法(或者从
Gdx.graphics.getDeltaTime()
,如中所示
this tutorial
(这有点过时,但仍然可以使用……):
// in you Enemy class
private float animationStateTime = 0f;
private Animation<TextureRegion> animation;
private SpriteBatch spriteBatch = new SpriteBatch();
public Enemy(Animation<TextureRegion> animation) {
this.animation = animation;
}
public void draw() {
animationStateTime += Gdx.graphics.getDeltaTime(); // a bit outdated, but working
// get the current frame of the animation for this enemy
TextureRegion currentFrame = animation.getKeyFrame(animationStateTime);
// draw the texture region (TODO this must probably be changed to not only draw the enemy at (50, 50))
spriteBatch.begin();
spriteBatch.draw(currentFrame, 50, 50); // Draw current frame at (50, 50)
spriteBatch.end();
}