Animation Class
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class Player {
private Animation<TextureRegion> walkAnimation;
private float stateTime;
public Player() {
Texture sheet = new Texture("player.png");
TextureRegion[][] tmp = TextureRegion.split(sheet, 32, 32);
TextureRegion[] walkFrames = new TextureRegion[4];
for (int i = 0; i < 4; i++) {
walkFrames[i] = tmp[0][i];
}
walkAnimation = new Animation<>(0.1f, walkFrames);
walkAnimation.setPlayMode(Animation.PlayMode.LOOP);
stateTime = 0f;
}
public void update(float delta) {
stateTime += delta;
}
public void render(SpriteBatch batch) {
TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime);
batch.draw(currentFrame, x, y);
}
}
Multiple Animations
public class Player {
private Animation<TextureRegion> idleAnimation;
private Animation<TextureRegion> walkAnimation;
private Animation<TextureRegion> jumpAnimation;
private Animation<TextureRegion> currentAnimation;
private float stateTime;
public void setState(String state) {
switch(state) {
case "idle":
currentAnimation = idleAnimation;
break;
case "walk":
currentAnimation = walkAnimation;
break;
case "jump":
currentAnimation = jumpAnimation;
break;
}
stateTime = 0;
}
public void render(SpriteBatch batch) {
TextureRegion frame = currentAnimation.getKeyFrame(stateTime, true);
batch.draw(frame, x, y);
}
}
Texture Atlas
public class AnimationManager {
private TextureAtlas atlas;
private Animation<TextureAtlas.AtlasRegion> animation;
public AnimationManager() {
atlas = new TextureAtlas("animations.atlas");
Array<TextureAtlas.AtlasRegion> frames = atlas.findRegions("walk");
animation = new Animation<>(0.1f, frames, Animation.PlayMode.LOOP);
}
public void dispose() {
atlas.dispose();
}
}
Tween Animations
import aurelienribon.tweenengine.*;
Tween.to(sprite, SpriteAccessor.POSITION_XY, 1.0f)
.target(400, 300)
.ease(TweenEquations.easeInOutQuad)
.start(tweenManager);
Tween.to(sprite, SpriteAccessor.SCALE_XY, 0.5f)
.target(2, 2)
.start(tweenManager);
Timeline.createSequence()
.push(Tween.to(sprite, SpriteAccessor.POSITION_Y, 1.0f).target(400))
.push(Tween.to(sprite, SpriteAccessor.ALPHA, 0.5f).target(0))
.start(tweenManager);
Best Practices
- Usa TextureAtlas per performance
- PlayMode.LOOP per animazioni cicliche
- Reset stateTime quando cambi animazione
- Dispose atlas quando non serve