Trying to have a 2-d, top down sprite that rotates and is animated, i have the main class where it is rendered, and a separate 'assets' class where it is created. The rotation works, however the sprite stays on the same frame. I used the libgdx wiki to try and animate my sprite https://github.com/libgdx/libgdx/wiki/2D-Animation
Here is the code in the assets class:
public class Asset implements ApplicationListener, Screen{
public static Texture walkSheet;
private static final int FRAME_COLS = 4;
private static final int FRAME_ROWS = 2;
static Animation walkAnimation;
static TextureRegion[] walkFrames;
static TextureRegion currentFrame;
static SpriteBatch spriteBatch;
static float stateTime;
public static void load(){
walkSheet = new Texture(Gdx.files.internal(".png"));
TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth()/FRAME_COLS, walkSheet.getHeight()/FRAME_ROWS); // #10
walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < FRAME_COLS; j++) {
walkFrames[index++] = tmp[i][j];
}
}
walkAnimation = new Animation(0.1f, walkFrames); // #11
spriteBatch = new SpriteBatch(); // #12
stateTime = 0f;
stateTime += Gdx.graphics.getDeltaTime();
currentFrame = walkAnimation.getKeyFrame(stateTime, true);
}
And here is how it is rendered:
game.batch.draw(Asset.currentFrame, x, y, (float)85, (float)85, (float)170, (float)170, (float)1, (float)1, (float)angleDegrees + 270);
What do i need to do to correctly animate the sprite?
The frame will never animate because you are not updating it. In the load()
method you did the following:
stateTime += Gdx.graphics.getDeltaTime();
currentFrame = walkAnimation.getKeyFrame(stateTime, true);
but this will get executed only once when you call the load()
method.
As your Asset
class implements the Screen
interface you must have implemented the abstract method render(float delta)
, so you need to update the frame in that method as follows:
public void render(float delta)
{
stateTime += delta;
currentFrame = walkAnimation.getKeyFrame(stateTime, true);
// Then render the frame as follows
batch.draw(currentFrame, x, y, (float)85, (float)85, (float)170, (float)170, (float)1, (float)1, (float)angleDegrees + 270);
}