Android 中的弹跳球跳过速度
Bouncing ball in Android skips velocity
我有一个只沿直线移动的球,它从屏幕的顶部和底部弹跳。每次这样做时,速度都会降低 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()
}
你可以尝试以下方法吗:
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()
}
我有一个只沿直线移动的球,它从屏幕的顶部和底部弹跳。每次这样做时,速度都会降低 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()
}
你可以尝试以下方法吗:
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()
}