Which is the best way to draw objects in pygame?
1) Drawing on a surface and then flipping it into a display.
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player, self).__init__()
self.surf = pygame.Surface((75, 25))
self.surf.fill((255, 255, 255))
self.rect = self.surf.get_rect()
player = Player()
screen.blit(player.surf, player.rect)
2) Directly drawing onto the display.
pygame.draw.rect(screen, color, (x,y,width,height), thickness)
What's the difference between the two methods and which is preferred and why?
Also which one is faster?
If you want to work with pygame.sprite.Group
then you should prefer to work with pygame.sprite.Sprite
object, because you can add the object to a group.
When you use a group, then you can use the .update()
to update all the Sprites in the Group and the draw()
method to draw all the Sprites in the Group.
But note, the draw()
method of pygame.sprite.Group
uses the .rect
and .image
attribute of the object, thus you have to rename .surf
to .image
. For instance:
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((75, 25))
self.image.fill((255, 255, 255))
self.rect = self.image.get_rect(center = (x, y))
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_d]
self.rect.x += 1
# [...]
screen = pygame.display.set_mode((width, height))
# [...]
my_group = pygame.sprite.Group()
my_group.add(Player(player_x, player_y))
while True:
# [...]
my_group.update()
# [...]
my_group.draw(screen)