Reputation: 396
I'm trying to load an explosion animation. The animations consists of 16 frames, all saved in the file Explosion.png. In my game, all the images are stored in a texture atlas pack.
So first i got the region that i needed from the class Assets.java
public class Explosion {
public final AtlasRegion explosion;
public Explosion (TextureAtlas atlas){
explosion = atlas.findRegion(Constants.EXPLOSION);
}
}
Then in my class which will create the explosion, I have the following code:
public Particles(Vector2 position){
this.position = position;
startTime = TimeUtils.nanoTime();
Array<TextureRegion> explosionAnimationTexture = new Array<TextureRegion>();
TextureRegion region = Assets.instance.explosion.explosion;
Texture explosionTexture = region.getTexture();
int ROW = 4; // rows of sprite sheet image
int COLUMN = 4;
TextureRegion[][] tmp = TextureRegion.split(explosionTexture, explosionTexture.getWidth() / COLUMN, explosionTexture.getHeight() / ROW);
TextureRegion[] frames = new TextureRegion[ROW * COLUMN];
int elementIndex = 0;
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
explosionAnimationTexture.add(tmp[i][j]);
frames[elementIndex++] = tmp[i][j];
}
}
explosion = new Animation(EXPLOSION_FRAME_DURATION,explosionAnimationTexture , Animation.PlayMode.LOOP_PINGPONG);
}
I'm using 4x4 since I have 16 frame. And inside the render method i got the following:
public void render(SpriteBatch batch){
float elapsedTime = MathUtils.nanoToSec * (TimeUtils.nanoTime() - startTime);
TextureRegion walkLoopTexture = explosion.getKeyFrame(elapsedTime);
batch.draw(
walkLoopTexture.getTexture(),
position.x,
position.y,
0,
0,
walkLoopTexture.getRegionWidth(),
walkLoopTexture.getRegionHeight(),
0.3f,
0.3f,
0,
walkLoopTexture.getRegionX(),
walkLoopTexture.getRegionY(),
walkLoopTexture.getRegionWidth(),
walkLoopTexture.getRegionHeight(),
false,
false);
}
The animation is working, however the images are loading from the whole atlas file, and not only Explosion.png as specified in step 1.
Upvotes: 0
Views: 663
Reputation: 20140
Code inside your Particles
class :
TextureRegion region = Assets.instance.explosion.explosion;
TextureRegion[][] tmp = TextureRegion.split(explosionTexture, explosionTexture.getWidth() / COLUMN, explosionTexture.getHeight() / ROW);
replace with :
TextureRegion[][] tmp = region.split(region.getRegionWidth()/COLUMN,region.getRegionHeight()/ROW);
And
draw your Animation
using textureRegion
instead of his texture
so choose appropriate method signature of SpriteBatch
for drawing textureRegion.
Upvotes: 2