使用Pygame检测对象与矩形的碰撞
是的,我又在问这个程序的问题了 :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)))
2 个回答
2
你只需要获取x和y的值,然后进行比较:
if pipe.x < bird.x < pipe.x+pipe.width:
#collision code
pass
4
一张图片本身是没有位置的。你不能在没有放置在世界中的东西之间测试碰撞。建议你创建一个鸟的类(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"
编辑:
不要害怕使用类,迟早你都会用到它们。如果你真的不想使用精灵(sprites),你可以用鸟的矩形和管道的矩形,调用collide_rect
来检查它们是否重叠。
编辑2:
这是一个从pygame文档修改过的鸟类(Bird class)的例子:
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)