使用TextureAtlas

时间:2017-08-03 14:02:46

标签: java android libgdx

我正在尝试加载爆炸动画。动画由16帧组成,全部保存在Explosion.png文件中。在我的游戏中,所有图像都存储在纹理图集包中。

首先,我从Assets.java类中获得了我需要的区域

public class Explosion {
    public final AtlasRegion explosion;
    public Explosion (TextureAtlas atlas){
        explosion = atlas.findRegion(Constants.EXPLOSION);
    }
}

然后在我的班级中会产生爆炸,我有以下代码:

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);
}

我使用的是4x4,因为我有16帧。在render方法中,我得到了以下内容:

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);

}

动画正在运行,但图像是从整个地图集文件加载的,而不仅是步骤1中指定的Explosion.png。

1 个答案:

答案 0 :(得分:2)

Particles课程内的代码:

TextureRegion region = Assets.instance.explosion.explosion;
TextureRegion[][] tmp = TextureRegion.split(explosionTexture, explosionTexture.getWidth() / COLUMN, explosionTexture.getHeight() / ROW);

替换为:

TextureRegion[][] tmp = region.split(region.getRegionWidth()/COLUMN,region.getRegionHeight()/ROW);

并且

使用Animation而不是textureRegion来绘制texture,因此请选择SpriteBatch的适当方法签名来绘制textureRegion。