是的,我正在问有关该程序的另一个问题: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)))
图像本身没有位置。您无法测试矩形与未放置在世界中的物体之间的碰撞。我建议创建一个 Bird 类和 Pipe 类,它们都是 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"
EDIT:
不要害怕课程,无论如何你迟早都会用到它们。
如果你真的不想使用精灵,你可以使用小鸟矩形和管道并调用collide_rect
检查它们是否重叠。
EDIT2:
从 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()
然后,您可以添加诸如 move 之类的方法,这将利用重力将鸟向下移动。
这同样适用于Pipe
但您可以创建一个空的 Surface,并用颜色填充它,而不是加载图像。
image = pygame.Surface(width,height)
image.fill((0,200,30)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)