Sunday, June 22, 2014

[libgdx] day 8 – frame animations

Characters in games are most of the times animated by drawing every of their movement image by image. These image are as well called frames. As I’m a really bad artist, I took this spritesheet of the mummy from the mojam-game Catacomb Snatch from Mojang.
I seperated it into the frames. The frames that belong to one animation(like go right) I gave the same name (mommyright) and added _INDEX. So the texturepacker knows that these images belong together and we can later ask for them easily.


Defining an animation is easy:
Animation animUp=new Animation(0.2f,atlas.findRegions("mummyup"));
0.2f is the time a single frame is visible. As well we can define, that our animation should be looped.
animUp.setPlayMode(Animation.LOOP);
Animation.LOOP says, that after the last frame the first comes again. If you say Animation.LOOP_PINGPONG after the last frame the order is reversed, so you got kind of a ping pong loop. Then there are as well the settings LOOP_REVERSED, LOOP_RANDOM, REVERSED and of course NORMAL.
To draw the right frame, we have to count the time and draw the fitting TextureRegion.
float animTime;
// [...]
animTime+=Gdx.graphics.getDeltaTime();
stage.getSpriteBatch().draw(animUp.getKeyFrame(animTime), 50,50);
If you combine that with some input-logic, you can turn the mummy into all directions.
testAnimUp=new Animation(0.2f, atlas.findRegions("mummyup"));
testAnimLeft=new Animation(0.2f, atlas.findRegions("mummyleft"));
testAnimDown=new Animation(0.2f, atlas.findRegions("mummydown"));
testAnimRight=new Animation(0.2f, atlas.findRegions("mummyright"));
// [...]
if(Gdx.input.isKeyPressed(Keys.UP)){
 direction=0;
}else if(Gdx.input.isKeyPressed(Keys.LEFT)){
 direction=1;
}else if(Gdx.input.isKeyPressed(Keys.DOWN)){
 direction=2;
}else if(Gdx.input.isKeyPressed(Keys.RIGHT)){
 direction=3;
}
// [...]
switch(direction){
 case 0:
  stage.getSpriteBatch().draw(testAnimUp.getKeyFrame(animTime,true), 50,50);
  break;
 case 1:
  stage.getSpriteBatch().draw(testAnimLeft.getKeyFrame(animTime,true), 50,50);
  break;
 case 2:
  stage.getSpriteBatch().draw(testAnimDown.getKeyFrame(animTime,true), 50,50);
  break;
 case 3:
  stage.getSpriteBatch().draw(testAnimRight.getKeyFrame(animTime,true), 50,50);
  break;
}

At the moment I’m still trying to combine this with the actors of scene2d. If I succeed, I’m going to add this later today.

No comments:

Post a Comment

Popular Posts