Pygame与对象的碰撞检测

2024-09-22 16:41:53 发布

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

是的,我在问关于这个项目的另一个问题:D

无论如何,我现在是一个程序,在屏幕上创建两行,它们之间有一个间隙,可以滚动。从这里,我显然需要看看这两个物体是否相撞。因为我只有一个雪碧和一个长方形,所以我认为为它们创建两个类有点毫无意义,而且太过分了。但是,我只能找到与我显然不需要的课程相关的教程。所以,我的问题是: 是否可以测试标准图像和Pygame之间的冲突rect?如果不是,我如何转换图像、矩形或两个精灵来执行此操作。(最好不要上课。)

注意:图像和矩形是按以下方式创建的(如果有区别的话)

bird = pygame.image.load("bird.png").convert_alpha()
pipeTop = pygame.draw.rect(screen, (0,200,30), Rect((scrollx,0),(30,height)))
pipeBottom = pygame.draw.rect(screen, (0,200,30), Rect((scrollx,900),(30,-bheight)))

Tags: 项目rect图像程序屏幕screenpygame物体
2条回答

图像本身没有位置。不能测试rect与未放置在世界中的对象之间的碰撞。我建议创建一个类Bird和一个类管道,这两个子类都是pygame.Sprite。

Pygame已经内置了碰撞检测。

一个简短的例子

bird = Bird()
pipes = pygame.Group()
pipes.add(pipeTop)
pipes.add(pipeBottom)

while True:    
    if pygame.sprite.spritecollide(bird,pipes):
        print "Game Over"

编辑:

别害怕上课,你迟早会用到的。 如果您真的不想使用sprite,可以使用birds rect和pipe并调用collide_rect来检查它们是否重叠。

编辑2:

从pygame文档修改的一个示例Bird类

class Bird(pygame.sprite.Sprite):
    def __init__(self):
       pygame.sprite.Sprite.__init__(self)

       self.image = pygame.image.load("bird.png").convert_alpha()

       # Fetch the rectangle object that has the dimensions of the image
       # Update the position of this object by setting the values of rect.x and rect.y
       self.rect = self.image.get_rect()

然后你可以添加一些方法,比如移动,这将使鸟在重力的作用下向下移动。

这同样适用于Pipe,但是您可以创建一个空曲面,并用颜色填充它,而不是加载图像。

image = pygame.Surface(width,height)
image.fill((0,200,30)

您只需获取x和y值并进行比较:

if pipe.x < bird.x < pipe.x+pipe.width:
    #collision code
    pass

相关问题 更多 >