Skip to main content
 首页 » 编程设计

python之如何在 Pygame 中分配和测试矩形的属性

2025年05月04日11zhengyun_ustc

这个问题不需要代码,尽管这是一个我在其他地方找不到答案的问题。

如何在 Pygame 中仅在矩形的边缘上测试矩形的碰撞?我看过 http://www.pygame.org/docs/ref/rect.html感觉答案就在那里,但我就是看不到。这非常重要,我希望这是一个简单的解决方案,并且是可回答的。

if <rectname>.colliderect.bottom(<otherRect>): 
    output = True 

^ 不起作用,但我怀疑答案可能相似。如果有人可以提供帮助,请提前致谢!

请您参考如下方法:

碰撞检测是一个广泛的话题,尤其是如果您想知道从哪一侧发生了收集。 (平台中的一种常见方法是进行两次碰撞检测,一次用于水平运动,一次用于垂直运动,如 this example 中所示)。

如果您只想知道一个 Rect 是否与另一个 Rect 的底部发生碰撞,下面的示例代码应该是一个很好的起点:

def collide_top(a, b): 
    return a.top <= b.bottom <= a.bottom and (a.left <= b.left <= a.right or b.left <= a.left <= b.right) 
def collide_bottom(a, b): 
    return a.bottom >= b.top >= a.top and (a.left <= b.left <= a.right or b.left <= a.left <= b.right) 
def collide_left(a, b): 
    return a.left <= b.right <= a.right and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom) 
def collide_right(a, b): 
    return a.right >= b.left >= a.left and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom) 
 
import pygame 
from pygame.locals import * 
 
pygame.init() 
screen = pygame.display.set_mode((300, 300)) 
clock = pygame.time.Clock() 
 
center = Rect((100, 100, 100, 100)) 
player = Rect((10, 0, 75, 75)) 
 
move = {K_UP:    ( 0, -1), 
        K_DOWN:  ( 0,  1), 
        K_LEFT:  (-1,  0), 
        K_RIGHT: ( 1,  0)} 
 
while True: 
    screen.fill((0, 0 ,0)) 
    pressed = pygame.key.get_pressed() 
    for d in [m for (k, m) in move.items() if pressed[k]]: 
      player.move_ip(*d) 
    pygame.draw.rect(screen, (120, 0, 120), center, 3) 
    pygame.draw.rect(screen, (0, 200, 55), player, 2) 
    # check if 'player' collides with the bottom of 'center' 
    print collide_bottom(center, player) 
    pygame.display.flip() 
    if pygame.event.get(QUIT): break 
    pygame.event.poll() 
    clock.tick(60) 

(在这张图片中,player 与 center 的底部和左侧发生碰撞,但没有与顶部或右侧发生碰撞)

一些进一步的问题:

当一个矩形完全位于另一个矩形内时会发生什么?在这种情况下,它是与所有边缘发生碰撞还是没有发生碰撞?


回应您的comment :

您可以简单地将碰撞检查更改为

def collide_top(a, b): 
    return a.top == b.bottom and (a.left <= b.left <= a.right or b.left <= a.left <= b.right) 
def collide_bottom(a, b): 
    return a.bottom == b.top and (a.left <= b.left <= a.right or b.left <= a.left <= b.right) 
def collide_left(a, b): 
    return a.left == b.right and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom) 
def collide_right(a, b): 
    return a.right == b.left and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)