【问题标题】:Bouncing ball in Android skips velocityAndroid中的弹跳球跳过速度
【发布时间】:2019-07-03 03:42:59
【问题描述】:

我有一个只能沿直线移动的球,它会从屏幕的顶部和底部反弹。每次这样做,速度都会减 2。球的半径为 50。

它工作正常,但是当速度达到 4 并撞到下一个墙壁时,它会变为 0 而不是 2,然后在下一次撞到墙壁时变为 0。

这是为什么呢?

private fun update() {
    if (ball.posy > 0) {
        if (ball.direction == "+") {
            ball.posy += ball.velocity
        } else {
            ball.posy -= ball.velocity
        }
    }
    if (ball.posy >= height - 50) {
        ball.direction = "-"
        ball.velocity -= 2
    } else if (ball.posy <= 50) {
        ball.direction = "+"
        ball.velocity -= 2
    }
    invalidate()
}

【问题讨论】:

    标签: android canvas kotlin draw


    【解决方案1】:

    您可以尝试以下方法吗:

    private fun update() {
        if (ball.posy > 0) {
            if (ball.direction == "+") {
                ball.posy = min(ball.posy + ball.velocity, height - 50)
            } else {
                ball.posy = max(ball.posy - ball.velocity, 50)
            }
        }
        if (ball.posy >= height - 50) {
            ball.direction = "-"
            ball.velocity -= 2
        } else if (ball.posy <= 50) {
            ball.direction = "+"
            ball.velocity -= 2
        }
        invalidate()
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-22
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多