In this tutorial, we look at animating sprites using the Animation class. We look at loading sprites two different ways. First creates them by splitting up a Texture loaded into memory. The second example uses a texture atlas. As always the code is provide below.
You can watch the video in HD here.
The Source
Example 1:
package com.gamefromscratch; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class AnimationDemo extends ApplicationAdapter { SpriteBatch batch; Texture img; TextureRegion[] animationFrames; Animation animation; float elapsedTime; @Override public void create () { batch = new SpriteBatch(); img = new Texture("walkcycle.png"); TextureRegion[][] tmpFrames = TextureRegion.split(img,256,256); animationFrames = new TextureRegion[4]; int index = 0; for (int i = 0; i < 2; i++){ for(int j = 0; j < 2; j++) { animationFrames[index++] = tmpFrames[j][i]; } } animation = new Animation(1f/4f,animationFrames); } @Override public void render () { elapsedTime += Gdx.graphics.getDeltaTime(); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(animation.getKeyFrame(elapsedTime,true),0,0); batch.end(); } }
Example 2:
package com.gamefromscratch.com; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; public class TextureAtlasAnimationDemo extends ApplicationAdapter { SpriteBatch batch; private TextureAtlas textureAtlas; private Animation animation; private float elapsedTime = 0f; @Override public void create () { batch = new SpriteBatch(); textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/myspritesheet.atlas")); animation = new Animation(1f/15f, textureAtlas.getRegions()); } @Override public void dispose() { batch.dispose(); textureAtlas.dispose(); } @Override public void render () { elapsedTime += Gdx.graphics.getDeltaTime(); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(animation.getKeyFrame(elapsedTime,true),0,0); batch.end(); } }
Programming LibGDX Video Tutorial Java