En este tutorial, observamos animar sprites usando la clase Animation. Nos fijamos en la carga de sprites de dos maneras diferentes. Primero los crea dividiendo una textura cargada en la memoria. El segundo ejemplo utiliza un atlas de texturas. Como siempre, el código se proporciona a continuación.
Tú puedes ver el video en HD aqui.
La fuente
Ejemplo 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(); } }
Ejemplo 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(); } }
Programación LibGDX Video Tutorial Java