【问题标题】:Libgdx - Animation only plays for 1 second inside if statementLibgdx - 动画在 if 语句中仅播放 1 秒
【发布时间】:2021-11-22 19:58:10
【问题描述】:

基本上,当球击中顶墙时。我想让它制作一些雷击动画,但动画只持续大约 1 秒。

if(ball.getY() + ball.getHeight() > topWall.getY()) {

        game.getBatch().draw(animation.getKeyFrame(timepassed, false), ball.getX(), ball.getY() + ball.getHeight(), 0, 0, leftWall.getWidth(), leftWall.getHeight() * -1, 1, 1, 0f);
        LightingStrikeRectArrayList.add(new Rectangle(ball.getX(), Apm.HEIGHT - ball.getY() + ball.getHeight() / 2, topWall.getWidth(), topWall.getHeight()));

            for (Rectangle rect : LightingStrikeRectArrayList) {
                if (rect.overlaps(playerHitbox)) {
                    this.game.setScreen(new GameScreen(this.game));
                }
            }
            
        if(!(LightingStrikeRectArrayList.isEmpty() && animation.isAnimationFinished(timepassed))) {
            LightingStrikeRectArrayList.remove(0);
        }
        ball.reverseDirectionY();
    }

【问题讨论】:

  • 只有当球仍在顶壁时才绘制异常,因为它在 if 块中。由于ball.reverseDirectionY(),我会假设球向下移动并且不再绘制动画,因为跳过了 if 块。
  • 是的,我需要球在碰撞时反转,因为球会在墙上反弹。
  • 将闪电绘图代码移出if-block。

标签: libgdx


【解决方案1】:

问题似乎是只要球在顶部,您就只能绘制动画。当球向下移动时,动画停止。

如果你设置了一个布尔变量,表示球正在接触顶壁,并且只要设置了这个标志就绘制动画,如果球向下移动,它将继续绘制事件。

解决方案可能类似于:

// create a global variable somewhere in the class, to store the flag
private boolean ballTouchedTopWall = false;

public void processGame() {
    
    //...

    if(ball.getY() + ball.getHeight() > topWall.getY()) {

        // set the flag instead of drawing the animation
        ballTouchedTopWall = true;

        LightingStrikeRectArrayList.add(new Rectangle(ball.getX(), Apm.HEIGHT - ball.getY() + ball.getHeight() / 2, topWall.getWidth(), topWall.getHeight()));

            for (Rectangle rect : LightingStrikeRectArrayList) {
                if (rect.overlaps(playerHitbox)) {
                    this.game.setScreen(new GameScreen(this.game));
                }
            }
            
        if(!(LightingStrikeRectArrayList.isEmpty() && animation.isAnimationFinished(timepassed))) {
            LightingStrikeRectArrayList.remove(0);
        }
        ball.reverseDirectionY();
    }

    if (ballTouchedTopWall) {
        game.getBatch().draw(animation.getKeyFrame(timepassed, false), ball.getX(), ball.getY() + ball.getHeight(), 0, 0, leftWall.getWidth(), leftWall.getHeight() * -1, 1, 1, 0f);
        
        // reset the flag when the animation ends
        if (animation.isAnimationFinished(timepassed)) {
            ballTouchedTopWall = false;
        }
    }
}

【讨论】:

  • 这有效,但仅当球第一次接触顶壁时。动画第一次结束后,连续动画为 1 秒。我尝试将所有逻辑部分(除了 flag/ball.reverseDirectionY();)移动到第二个 if 语句中,但这也不起作用
  • 也许你需要在小球碰到顶壁时将timepassed变量重置为0?
猜你喜欢
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
相关资源
最近更新 更多