0

I have a sprite that i want to rotate when i hit he left and right arrow but when i rotate it it moves a little bit. my code is shown bellow

class Ship(pygame.sprite.Sprite):
    def __init__(self,color):
        super().__init__()
        self.image=pygame.image.load("ship.png")
        self.colorlayer=pygame.image.load("shipcolor.png")
        self.rect = self.image.get_rect()
        self.x=400
        self.y=300
        self.angle_delta = 0

    def drawsprite(self,surface):
        old_image_center = self.rect.center
        new_image = pygame.image.load("ship.png")
        new_colorlayer = pygame.image.load("shipcolor.png")
        self.image = pygame.transform.rotate(new_image, self.angle_delta)
        self.colorlayer = pygame.transform.rotate(new_colorlayer, self.angle_delta)
        self.rect = self.image.get_rect()
        self.rect.center = old_image_center
        surface.blit(self.colorlayer,(self.x, self.y))
        surface.blit(self.image,(self.x, self.y))


    def rotate(self):
        if event.type == pygame.KEYDOWN:
            if event.key== pygame.K_RIGHT:
                self.angle_delta += 45
            if event.key== pygame.K_LEFT:
                self.angle_delta -=45
Lux
  • 13
  • 4
  • When the image rotates, it's dimensions, and therefore it's centre changes. You need to remember the current position, rotate the image, then reset the position based on the centre. – Kingsley Feb 27 '19 at 23:44
  • is there a way you would recommend doing this – Lux Feb 27 '19 at 23:52

1 Answers1

0

When an image rotates, its size, and therefore centre-point changes.

One way to rotate about a centre-point is to remember the centre-point before the rotation, then re-apply it after the rotation.

class SomeSprite( pygame.sprite.Sprite ):
    def __init__( self, x, y ):
        self.original_image = pygame.image.load("some_filename.png").convert_alpha()
        self.image          = self.original_image
        self.rect           = self.image.get_rect()
        self.rect.center    = ( x, y )

    def rotateTo( self, angle ):
        # rotate and zoom the sprite, starting with an original image
        # this prevents image degradation
        self.image = pygame.transform.rotozoom( self.original_image, angle, 1 )
        # reset it back to original centre
        self.rect  = self.image.get_rect( center=self.rect.center )

Obviously, if the image subject is not centred within the surrounding bitmap, it will definitely rotate about its centre, but still look like that's not the case.

Kingsley
  • 14,398
  • 5
  • 31
  • 53