首先,我会说我很累,我已经大约22个小时了。无论如何,我在PONG游戏中有这个时髦的物理问题。你知道古老的经典。我一直在寻找代码,尝试不同的变化,评论某些部分等等,我找不到该死的bug!
有人可以帮我一把吗?
这是球的物理问题。当向左走时,它会从屏幕的顶部和底部弹回。
但是当我从左边碰到碰撞后,我无法将它发回到右边。它只是强行反弹并迫使它回到桨上?!
然而,当我将球打到右侧击中顶部或底部之一后,我可以正确地发球,所以我认为将球移到右边的实际代码没有任何问题。 / p>
但是向右移动是与游戏所需物理学相反的,所以它没用,因为当它击中左边的划桨时它应该反弹并向右移动,它不应该“强迫”它自己划桨然后向左走。
如果你能看到它,它实际上很有趣:)
任何人都可以理解这一点并给我一个解释吗?
[代码]
# move the ball around
# if the ball disappears off the either side of the screen, send it back heading left
if ballRect.left > WINDOWWIDTH or ballRect.right < 0:
direction = getRandomDirection()
ballRect.center = (WINDOWWIDTH - ballRect.width, random.randint(100, 200))
if direction == 'downleft':
ballRect.left -= BALLSPEEDX
ballRect.top += BALLSPEEDY
if direction == 'upleft':
ballRect.left -= BALLSPEEDX
ballRect.top -= BALLSPEEDY
if direction == 'downright':
ballRect.left += BALLSPEEDX
ballRect.top += BALLSPEEDY
if direction == 'upright':
ballRect.left += BALLSPEEDX
ballRect.top -= BALLSPEEDY
if ballRect.top < 0:
if direction == 'upleft':
direction = 'downleft'
if direction == 'upright':
direction = 'downright'
if ballRect.bottom > WINDOWHEIGHT:
if direction == 'downleft':
direction = 'upleft'
if direction == 'downright':
direction = 'upright'
if paddleRect.colliderect(ballRect):
if direction == 'upleft':
direction = 'upright'
ballRect.left += BALLSPEEDX
ballRect.top -= BALLSPEEDY
if direction == 'upright':
direction = 'upleft'
ballRect.left += BALLSPEEDX
ballRect.top -= BALLSPEEDY
if direction == 'downleft':
direction = 'upleft'
ballRect.left += BALLSPEEDX
ballRect.top += BALLSPEEDY
if direction == 'downright':
direction = 'upright'
ballRect.left -= BALLSPEEDX
ballRect.top += BALLSPEEDY
[/代码]
答案 0 :(得分:4)
如果directions == 'upleft'
,这两个块都将执行
if paddleRect.colliderect(ballRect):
if direction == 'upleft':
direction = 'upright'
ballRect.left += BALLSPEEDX * 4
ballRect.top -= BALLSPEEDY * 4
if direction == 'upright':
direction = 'upleft'
ballRect.left += BALLSPEEDX * 4
ballRect.top -= BALLSPEEDY * 4
可能应该更像这样
if paddleRect.colliderect(ballRect):
if direction == 'upleft':
direction = 'upright'
ballRect.left += BALLSPEEDX * 4
ballRect.top -= BALLSPEEDY * 4
elif direction == 'upright':
direction = 'upleft'
ballRect.left += BALLSPEEDX * 4
ballRect.top -= BALLSPEEDY * 4
elif ...
答案 1 :(得分:0)
如果您删除direction
,则可以像这样反弹:
if collide with left/right wall:
xvel *= -1
if collide with top/bot wall:
yvel *= -1
# then always
ball.rect.left += xvel
ball.rect.top += yvel