繁体   English   中英

Pygame-为动态绘制的对象获取矩形

[英]Pygame - Getting a rectangle for a dynamically drawn object

我正在为即将出版的书籍编写一个简单的Pygame教程,但在此问题上,我有点受阻。 我有两个班级,一个球(波拉)和一个桨(拉奎特)。 球形精灵来自图像,其类别非常简单:

class bola(pygame.sprite.Sprite):

    def __init__(self, x, y, imagem_bola):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.image = pygame.image.load(imagem_bola)
        self.rect = self.image.get_rect()

    def imprime(self):
        cenario.blit(self.image, (self.x, self.y))

但是,随着球拍的高度和宽度作为参数传递,球拍会动态绘制。

class raquete(pygame.sprite.Sprite):

    def __init__(self, x, y, l_raquete, a_raquete):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.l_raquete = l_raquete
        self.a_raquete = a_raquete
        self.image = pygame.draw.rect(cenario, branco, (self.x, self.y, self.l_raquete, self.a_raquete))
        self.rect = self.image.get_rect()  # this doesn't work!

    def imprime(self):
        pygame.draw.rect(cenario, branco, (self.x, self.y, self.l_raquete, self.a_raquete)) 

如您所见,我尝试使用以下命令加载self.image

pygame.draw.rect(cenario, branco, self.x, self.y, self.l_raquete, self.a_raquete))

然后使用self.rect = self.image.get_rect()获取rect self.rect = self.image.get_rect()

当然,我不能让rectraquete ,碰撞也不起作用。

欢迎所有提示!

只需创建一个新的Surface并用正确的颜色填充它即可:

class raquete(pygame.sprite.Sprite):

    def __init__(self, x, y, l_raquete, a_raquete):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((l_raquete, a_raquete))
        # I guess branco means color
        self.image.fill(branco) 
        # no need for the x and y members, 
        # since we store the position in self.rect already
        self.rect = self.image.get_rect(x=x, y=y) 

由于您已经在使用Sprite类,因此imprime函数的意义何在? 只需使用pygame.sprite.Group将您的精灵绘制到屏幕上即可。 也就是说, Spriterect成员用于定位,因此您可以将bola类简化为:

class bola(pygame.sprite.Sprite):

    def __init__(self, x, y, imagem_bola):
        pygame.sprite.Sprite.__init__(self)
        # always call convert() on loaded images
        # so the surface will have the right pixel format
        self.image = pygame.image.load(imagem_bola).convert()
        self.rect = self.image.get_rect(x=x, y=y)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM