如何在Pygam中分配和测试rect上的属性

2024-03-28 11:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题不需要代码,尽管我在别处找不到答案。在

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

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

^不起作用,但我怀疑答案可能与此类似。如果有人能帮忙,请提前谢谢!在


Tags: 答案代码orgrectrefhttpdocsif
1条回答
网友
1楼 · 发布于 2024-03-28 11:39:06

碰撞检测是一个广泛的主题,特别是如果您想知道收集是从哪一边发生的。(平台格式中的一种常见方法是执行两次碰撞检测,一次用于水平运动,一次用于垂直运动,如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)

enter image description here

(在这张图片中,playercenter的底部和左侧碰撞,而不是与顶部或右侧碰撞)

一些进一步的问题:

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


针对您的comment

只需将碰撞检查更改为

^{pr2}$

相关问题 更多 >