Why my sprite in pygame every time it changes teleports for a millisecond to the top left edge?

Question:

This is not a problem in itself, because it does not affect anything in the gameplay, but it is a visual bug that bothers a lot, every time it changes state between crouching and standing, the Sprite teleports to the corner for 1 millisecond, is there any way How to avoid this? Here’s a piece of code that makes the sprite switch between crouching and standing.

if pressKeys[K_DOWN]:
   self.surf = self.crouch_sprites[0]
   self.surf = pygame.transform.scale(self.surf, (30, 15))
   self.rect = self.surf.get_rect()
   self.isCrouch = True
else:
   self.surf = self.run_sprites[0]
   self.surf = pygame.transform.scale(self.surf, (30, 30))
   self.rect = self.surf.get_rect()
   self.isCrouch = False

GIF showing the bug

Asked By: MDC

||

Answers:

pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. A Surface is blit at a position on the screen. You have set the position of the rectangle.

e.g.: Sets the position of the rectangle with its previous position:

self.rect = self.surf.get_rect()

self.rect = self.surf.get_rect(bottomleft = self.rect.bottomleft)

Fix in your code:

if pressKeys[K_DOWN]:
   self.surf = self.crouch_sprites[0]
   self.surf = pygame.transform.scale(self.surf, (30, 15))
   self.rect = self.surf.get_rect(bottomleft = self.rect.bottomleft)
   self.isCrouch = True
else:
   self.surf = self.run_sprites[0]
   self.surf = pygame.transform.scale(self.surf, (30, 30))
   self.rect = self.surf.get_rect(bottomleft = self.rect.bottomleft)
   self.isCrouch = False
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.