简体   繁体   中英

Sprite Animation Pictures are Overlapping

I'm trying to make an animation out of an png file, that has various states of an action. My problem is, that the pictures overlap each other while rendering. Is there a solution, where i can only show one picture? I use the LibGDX lib.

@Override public void show()
{
    batch = new SpriteBatch();
    img = new Texture("core/assets/ghosty.png");

    regions = TextureRegion.split(img, 32, 32);
    sprite = new Sprite (regions[0][0]);
    Timer.schedule(new Timer.Task(){

        @Override
        public void run(){
            frame++;
            if (frame>27){
                frame = 0;
                if (zeile ==1){
                    zeile = 0;
                }
                else
                {
                    zeile = 1;
                }
            }
            sprite.setRegion(regions[zeile][frame]);
        }

    }, 0, 1/20f);

}

@Override public void render(float delta)
{
    //stage.draw();

    batch.begin();

    sprite.draw(batch);

    batch.end();
}

You don't need an extra Timer task and a Sprite instead you need an Animation<> .

Here is a little example of how you render an Animation:

private SpriteBatch batch;
private Texture img;
private Animation<TextureRegion> animation;
private TextureRegion[][] regions;
private Array<TextureRegion> frames;

@Override
public void show() {
    batch = new SpriteBatch();
    img = new Texture(Gdx.files.internal("ghosty.png")); //Get Texture from asset folder
    regions = TextureRegion.split(img, 32, 32);
    frames = new Array<TextureRegion>();
    int rows = 5, columns = 5; //How many rows and columns the region have

    //Fill Frames array with the regions of Texture
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < columns; j++){
            frames.add(regions[i][j]);
        }
    }

    //Create Animation. 0.1f is the time how long a frame will occur,
    //is the animation to fast set this number to a higher value
    //so the single frames will stay for a longer time
    animation = new  Animation<TextureRegion>(0.1f, frames, Animation.PlayMode.LOOP);
}

private float stateTime = 0;

@Override
public void render(float delta) {
    //Clear the screen
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    //update state time so animation will go further
    stateTime += delta;

    batch.begin();
    //Draw the current frame
    batch.draw(animation.getKeyFrame(stateTime), 50, 50);
    batch.end();
}

Hope this will help you.

A more efficient and easier way to run animation is to use TextureAtlas instead of Texture . Here is an example for using TextureAtlas: Libgdx Animation not working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM