[英]Pygame - Getting a rectangle for a dynamically drawn object
I am writing a simple Pygame tutorial for an upcoming book and I am sort of blocked in this issue here. 我正在为即将出版的书籍编写一个简单的Pygame教程,但在此问题上,我有点受阻。 I have two classes, a ball (bola) and a paddle (raquete). 我有两个班级,一个球(波拉)和一个桨(拉奎特)。 The ball sprite comes from an image and its class is quite straightforward: 球形精灵来自图像,其类别非常简单:
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))
The racket, however, gets drawn dynamically as its height and width are passed as parameters. 但是,随着球拍的高度和宽度作为参数传递,球拍会动态绘制。
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))
As you can see, my attempt to load self.image
with 如您所见,我尝试使用以下命令加载self.image
pygame.draw.rect(cenario, branco, self.x, self.y, self.l_raquete, self.a_raquete))
and then get the rect
using self.rect = self.image.get_rect()
just doesn't work. 然后使用self.rect = self.image.get_rect()
获取rect
self.rect = self.image.get_rect()
。
Of course, as I cannot get the rect
for raquete
, collisions also don't work. 当然,我不能让rect
的raquete
,碰撞也不起作用。
All hints are welcome! 欢迎所有提示!
Just create a new Surface
and fill it with the right color: 只需创建一个新的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)
Since you're already using the Sprite
class, what's the point of the imprime
function anyway? 由于您已经在使用Sprite
类,因此imprime
函数的意义何在? Just use a pygame.sprite.Group
to draw your sprites to the screen. 只需使用pygame.sprite.Group
将您的精灵绘制到屏幕上即可。 That said, the rect
member of a Sprite
is used for positioning, so you can simplify your bola
class to: 也就是说, Sprite
的rect
成员用于定位,因此您可以将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.