Pygame 碰撞在检测到更多矩形时不会检测为碰撞



我在手机上制作碎砖器,遇到了一个问题。当ball rect位于2块砖的中间x时,它只忽略侧面碰撞:

for brick in bricks:
if brick.colliderect(ball):
#side collision
dr = abs(brick.right - ball.left)
dl = abs(brick.left - ball.right)
db = abs(brick.bottom - ball.top)
dt = abs(brick.top - ball.bottom)
if min(dl, dr) < min(dt, db):
speed[0]=-speed[0]
else:
speed[1]=-speed[1]

以某种方式检测到与collectrect的碰撞,但与侧面碰撞没有检测到。

问题是,您的算法会反转对象碰撞的每个矩形的移动方向。如果对象与同一方向的两个矩形碰撞,则末端的移动方向为原始方向。可能有几个选项2来解决问题:

尝试1:break第一次检测到碰撞后的循环:

for brick in bricks:
if brick.colliderect(ball):
#side collision
dr = abs(brick.right - ball.left)
dl = abs(brick.left - ball.right)
db = abs(brick.bottom - ball.top)
dt = abs(brick.top - ball.bottom)
if min(dl, dr) < min(dt, db):
speed[0]=-speed[0]
else:
speed[1]=-speed[1]
break

尝试1:不要反转方向,而是根据碰撞的一侧设置方向:

for brick in bricks:
if brick.colliderect(ball):
#side collision
dr = abs(brick.right - ball.left)
dl = abs(brick.left - ball.right)
db = abs(brick.bottom - ball.top)
dt = abs(brick.top - ball.bottom)
if min(dl, dr) < min(dt, db):
speed[0] = -abs(speed[0]) if dl < dr else abs(speed[0])
else:
speed[0] = -abs(speed[1]) if dt < db else abs(speed[1])

最新更新