Search code examples
pythonpygamespritedraw

how to create a circular sprite in pygame


I've tried to make a circular sprite in pygame. My sprite class:

import pygame
WHITE = (255, 255, 255)

class player(pygame.sprite.Sprite):
    def __init__(self, color, width, height, speed):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the player, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        #Initialise attributes of the car.
        self.width = width
        self.height = height
        self.color = color
        self.speed = speed

        # Draw the player
        pygame.draw.circle(self.image,self.color,self.speed,5)

This returns the error:

line 23, in __init__
   pygame.draw.circle(self.image,self.color,self.speed,5)
TypeError: argument 3 must be 2-item sequence, not int

so I have been trying different sources but I can never seem to figure out how to do it. So how do you make a circular sprite? It doesn't need to move or anything - I just need a small(ish) sprite.


Solution

  • The 3rd argument of pygame.draw.circle() has to be a tuple with 2 components, the x and y center coordinated of the circle:

    pygame.draw.circle(self.image,self.color,self.speed,5)

    pygame.draw.circle(self.image, self.color, (self.width//2, self.height//2), 5)
    

    In the above example (self.width//2, self.height//2) is the center of the circle and 5 is the radius (in pixel).

    See also
    Pygame Wont Let Me Draw A Circle Error argument 3 must be sequence of length 2, not 4


    Furthermore a pygame.sprite.Sprite object should always have a .rect attribute (instance of pygame.Rect):

    class player(pygame.sprite.Sprite):
        def __init__(self, color, width, height, speed):
            # Call the parent class (Sprite) constructor
            super().__init__()
    
            # [...]
            
            pygame.draw.circle(self.image, self.color, (self.width//2, self.height//2), 5)
            self.rect = self.image.get_rect()
    

    Note, the .rect and .image attribute of the pygame.sprite.Sprite object is used by the .draw(), method of a pygame.sprite.Group to draw the contained sprites.

    Thus a sprite can be moved by changing the position (e.g. self.rect.x, self.rect.y) encoded in the rectangle.