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

Rotating a sprite on pygame

I have created a class for the zombie I blit into the screen, but the rotation does not work at all, it rotates a lot and moves the image around, is there some way to rotate the image around its center? how could I change the rotate def so that it works properly?

class zombieObj:
    def __init__(self, x, y, vel, angle):
      tempZombie = pygame.image.load('zombieSprite.png')
      self.zombieSpriteSurface = pygame.transform.scale(tempZombie, (64, 64))
      self.x = x
      self.y = y
      self.vel = 1
      self.angle = angle
    def rotate(self, image, angle):
      self.zombieSpriteSurface = pygame.transform.rotate(image, angle)

and this is how I called it in the loop:

zombieSprite.angle = zombieSprite.angle + 5
zombieSprite.rotate(zombieSprite.zombieSpriteSurface, zombieSprite.angle)

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 :

See How do I rotate an image around its center using PyGame?. The trick is to get the center of the image before rotation and set it after rotation. Also, you need to rotate the original image to avoid distortion:

class ZombieObj:
    def __init__(self, x, y, vel, angle):
        tempZombie = pygame.image.load('zombieSprite.png')
        self.originalImage = pygame.transform.scale(tempZombie, (64, 64))
        self.vel = 1
        self.angle = 0
        self.rect = self.originalImage.get_rect(topleft = (x, y))
        self.roatate(angle)

    def rotate(self, angle):
        self.angle = angle
        self.zombieSpriteSurface = pygame.transform.rotate(self.originalImage, self.angle)
        self.rect = self.zombieSpriteSurface.get_rect(center = self.rect.center)

If you want to increase the rotation by a certain angle, you need to add the additional angle to the current angle:

class ZombieObj:
    # [...]

    def rotate(self, delteAngle):
        self.angle += delteAngle
        self.zombieSpriteSurface = pygame.transform.rotate(self.originalImage, self.angle)
        self.rect = self.zombieSpriteSurface.get_rect(center = self.rect.center)
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