Libgdx animation is flickering when flipping

351 Views Asked by At

I have a character that has 2 animations both when idle and when walking. Whenever i press the left or right key the image is flipped in the direction i pressed. However the problem is that when implementing this with the idle animation it flickers yust a bit but fast, but the code works fine only the flickering part right after a flip for a split second is the problem.

this is the code:

elapsedTime += Gdx.graphics.getDeltaTime();

        Array<TextureAtlas.AtlasRegion> frames = textureAtlas.getRegions();

        animation = new Animation(1f/10f, textureAtlas.getRegions());

        for(TextureRegion frame: frames){
            if(body.getLinearVelocity().x > 0 && !frame.isFlipX()){
                frame.flip(true, false);

            } else if (body.getLinearVelocity().x < 0 && frame.isFlipX()){
                frame.flip(true, false);

            }
        }
2

There are 2 best solutions below

0
Tenfour04 On

It could be that you're seeing one frame of it facing the other way when it first comes to rest from walking the opposite direction from how you were facing the last time you were idle. You need to track which way the character is facing in a variable so whenever the velocity drops to zero, you still know which way to make it face.

private boolean wasFacingRight;

boolean isFacingRight;
if (body.getLinearVelocity().x > 0)
    isFacingRight = true;
else if (body.getLinearVelocity().x < 0)
    isFacingRight = false;
else
    isFacingRight = wasFacingRight; //not moving, keep facing the same way

//Don't need to iterate all frames of the animation since you're only drawing one
TextureRegion frame = animation.getFrame(elapsedTime);
if (frame.isFlipX() == isFacingRight)
    frame.flip(true, false);

wasFacingRight = isFacingRight;

An alternative solution that doesn't involve repeatedly flipping your animations is to simply draw your texture region flipped when you need to like this:

if (isFacingRight)
    batch.draw(region, x, y, width, height);
else
    batch.draw(region, x + width, y, -width, height);
0
Mingju Roberts On

There is a great tutorial on this on YouTube. Brent Aureli has done a whole series on recreating Super Mario in libgdx. Videos 10 and 11 deal with character animation and movement. You can find the video here https://youtu.be/1fJrhgc0RRw