翻转时,libgdx动画正在闪烁



我的角色在闲置和行走时都有2个动画。每当我按左右键时,图像就会以我按下的方向翻转。但是,问题是,在使用空闲动画实施此操作时,它会闪烁一点,但很快,但是该代码仅在翻转一秒钟后立即闪烁的部分工作正常。

这是代码:

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

可能是,当它第一次靠在相反的方向与上次闲置时面对面的方向相反的方向时,它会看到它的另一帧面向另一种方式。您需要跟踪角色在变量中面对的方式,因此每当速度下降到零时,您仍然知道将其面对面的方式。

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;

一种不涉及反复翻转动画的替代解决方案就是在需要时简单地绘制纹理区域的翻转:

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

在YouTube上有一个很棒的教程。布伦特·奥雷利(Brent Aureli(在Libgdx中重现超级马里奥(Super Mario(进行了整个系列。视频10和11处理角色动画和运动。您可以在此处找到视频https://youtu.be/1fjrhgc0rrw