2

I'm having a great difficulty to create a single sprite rotation using pygame.

I'm following this code (https://stackoverflow.com/a/47688650/5074998) to obtain a center rotation of a sprite. And here is my current code:

import pygame

FPS: int = 100
W = 600
H = 400
MAGENTA = (255, 0, 255)
BLACK = (0, 0, 0)

pygame.init()
screen = pygame.display.set_mode([W, H])
pygame.display.set_caption("Cars")
clock = pygame.time.Clock()


class sp():
    def __init__(self):
        self.image = pygame.Surface((122, 70), pygame.SRCALPHA)
        pygame.draw.polygon(self.image, pygame.Color('dodgerblue1'),
                            ((1, 0), (120, 35), (1, 70)))
        self.orig_image = self.image
        self.rect = self.image.get_rect(center=[W / 2, H / 2])
        self.angle = 0

    def update(self):
        self.angle += 2
        self.rotate()
        screen.blit(self.image, [100, 100])

    def rotate(self):
        self.image = pygame.transform.rotozoom(self.orig_image, self.angle, 1)
        self.rect = self.image.get_rect(center=self.rect.center)


sp1 = sp()
out = pause = False

while not out:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            out = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                pause = not pause
    if not pause:
        screen.fill(BLACK)
        sp1.update()
        pygame.display.flip()

But I can't understand why I get this:

enter image description here

Could anyone help me?

Rogério Dec
  • 801
  • 8
  • 31
  • Looks like your center of rotation is not in the center of mass or changing for each rotation step. – Joe Sep 20 '18 at 05:45

1 Answers1

2

That happens because you're blitting the self.image at the position [100, 100] instead of the self.rect (that means at the self.rect.topleft coordinates). The size of the image is different after each rotation and if you just blit it at the same top left coordinates, the image will wobble like that because the center is somewhere else each frame. You can see that by drawing the bounding rect at [100, 100]:

pygame.draw.rect(screen, (255, 0, 0), [(100, 100), self.image.get_size()], 1)

To fix this problem, you have to create a new rect each time and set its center coordinates to the center coords of the previous rect. That will adjust the topleft coordinates (where the image gets blitted) as well, so that the image stays centered. Then just blit the image at the rect:

screen.blit(self.image, self.rect)

Draw the self.rect to see how the topleft coord changes all the time now whereas the center won't move:

pygame.draw.rect(screen, (255, 0, 0), self.rect, 1)
skrx
  • 19,980
  • 5
  • 34
  • 48