簡體   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