2

I am trying to rotate an image in pycharm, for some reason when I rotate, the object wobbles and doesn't rotate in place.

class rocket(object):
def __init__(self, x, y):
    self.original_image = pygame.image.load('sprites/spaceship-off.png')
    self.image = self.original_image
    self.x = x
    self.y = y
    self.width = 50
    self.height = 50
    self.speed = 15
    self.angle = 0
    self.direction = [0, -1]
    self.position = [400, 400]

def draw(self, win):
    win.blit(self.image, (self.position))
    self.image = pygame.transform.rotate(self.original_image, self.angle)

-

if keys[pygame.K_a] and player.x > player.speed:
    player.angle += 10 % 360
if keys[pygame.K_d] and player.x < 800 - player.width - player.speed:
    player.angle -= 10 % 360
Neo630
  • 181
  • 1
  • 16

1 Answers1

1

When you want to rotate an image around its center, then you've to:

  • get the pivot (which is the center point of the not rotated image)
  • rotate the image and get the (axis aligned bounding) rectangle of the rotated image
  • center the rectangle to the pivot
  • blit the image at the top left of the new rectangle
def draw(self, win):

    image_rect = self.original_image.get_rect(topleft = self.position)
    pivot = image_rect.center

    self.image = pygame.transform.rotate(self.original_image, self.angle)
    rotated_rect = self.image.get_rect(center = pivot)

    win.blit(self.image, rotated_rect.topleft)

See also How do I rotate an image around its center using Pygame?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174