Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading