Home > OS >  Array of sprite animation libgdx
Array of sprite animation libgdx

Time:06-26

I'm trying to create a game for a university project. In the main menu, i animated a character with this:

spidey = new Texture("spidey.png");
TextureRegion[][] tmpFrames = 
TextureRegion.split(spidey,spidey.getWidth()/3,spidey.getHeight()/5);
animationFrames = new TextureRegion[15];
int index = 0;
for (int i=0; i<5; i  ){
    for (int j=0; j<3; j  ){
        animationFrames[index  ] = tmpFrames[i][j];
    }
}
animation = new Animation(0.15f, (Object[]) animationFrames);

But if i have an array of character like this:

public void characters() {
enemies = new Array<Enemy>();
enemies.add(new Enemy(new Sprite(new Texture("img1.png")), spawn));
enemies.add(new Enemy(new Sprite(new Texture("img2.png")), spawn));
enemies.add(new Enemy(new Sprite(new Texture("img3.png")), spawn));
enemies.add(new Enemy(new Sprite(new Texture("img4.png")), spawn));      
}

How can i animate all character?

CodePudding user response:

To use an animation for you enemy you don't need to create an Array of enemies, but an Animation object for an enemy, just like you did in the first code snippet in you question.

Something like this:

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);
}

Now you enemy needs to be able to draw the animation. Therefore you need to add a draw method that gets the delta time as a parameter (or you get the delta time from Gdx.graphics.getDeltaTime(), like in this tutorial (which is a bit outdated but should still work...):

// 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();
}
  • Related