Skip to content Skip to sidebar Skip to footer

Rotation Of A Sprite On A Circle

There's a sprite moving on a circle centered around the screen center with radius = 30 pixels. The movement is more or less OK, but the sprite doesn't rotate at all. I've tried som

Solution 1:

Read the documentation of pygame.sprite.Group.draw:

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.

Therefore, the rotated image must be stored in the image attribute. You will not see any rotation because you save the rotated image in the image2 attribute, but image is the originally rotated image. Store the original image in original_image and the rotated image in image:

classEnemiesStrong(pygame.sprite.Sprite):

    def__init__(self):
        pygame.sprite.Sprite.__init__(self)     
        self.image = pygame.image.load("enemy3.png").convert_alpha()
        self.image = self.original_image        
        self.rect = self.image.get_rect()  
        self.angle = 0defupdate(self):
        # [...]

        self.image = pygame.transform.rotate(self.original_image, self.angle)
        self.rect = self.image.get_rect(center = oldcenter)

        # [...]      

See also Move and rotate.


Minimal example:

import pygame

classEnemiesStrong(pygame.sprite.Sprite):

    def__init__(self):
        pygame.sprite.Sprite.__init__(self)     
        self.original_image = pygame.image.load(r"arrow_up.png").convert_alpha()
        self.image = self.original_image        
        self.rect = self.image.get_rect()  
        self.angle = 0definitLoc(self, pos, radius):
        self.pos = pos
        self.radius = radius

    defupdate(self):
        center = pygame.math.Vector2(self.pos) + pygame.math.Vector2(0, -self.radius).rotate(-self.angle) 
        self.image = pygame.transform.rotate(self.original_image, self.angle)
        self.rect = self.image.get_rect(center = (round(center.x), round(center.y)))            

    defturnLeft(self):
        self.angle = (self.angle + 1) % 360
   
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

enemy_s = EnemiesStrong()
enemy_s.initLoc(window.get_rect().center, 100)
all_sprites = pygame.sprite.Group(enemy_s)

run = Truewhile run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    enemy_s.turnLeft()
    all_sprites.update()

    window.fill(0)
    pygame.draw.circle(window, (127, 127, 127), window.get_rect().center, 100, 1)
    all_sprites.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

Post a Comment for "Rotation Of A Sprite On A Circle"