其他分享
首页 > 其他分享> > Pygame碰撞检测与对象和矩形

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)))

解决方法:

图像本身没有位置.您无法测试rect与世界上未放置的物体之间的碰撞.我建议创建一个类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"

编辑:

不要担心类,您迟早必须使用它们.
如果您真的不想使用精灵,则可以使用鸟rect和管道,并调用collide_rect来检查它们是否重叠.

EDIT2:

从pygame docs修改的示例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)

标签:python,pygame,collision-detection
来源: https://codeday.me/bug/20191011/1891208.html