sw123456
sw123456

Reputation: 3459

PyGame: Change the starting position of a sprites surface so it doesn't start at (0,0)

Is there a way to change the starting position of a sprite's surface?

For example, the code below is for a ball sprite. The ellipse is drawn at (50,50) but the surface of the sprite which the drawing is added to begins at (0,0) which means that only part of the ball is shown.

I need the ball sprites surface to start AWAY from the top left corner. Can this be done? If so, how?

My code:

class Ball(pygame.sprite.Sprite):
    """
    This class represents the ball.
    """
    def __init__(self, width, height):
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        pygame.draw.ellipse(self.image, (255,0,0), [50,50,width,height], 10)

        self.rect = self.image.get_rect()

Upvotes: 0

Views: 3523

Answers (1)

sw123456
sw123456

Reputation: 3459

Sloths comment struck a chord. I simply needed to rewrite the sprite's image's rect coordinates to get the surface spawning in a different position. So the ellipse coordinate returned to (0,0) so that it was drawn correctly on the sprite surface and the sprites rect coordinate was overwritten to (50,50):

pygame.draw.ellipse(self.image, (255,0,0), [0,0,width,height], 10)

# Fetch the rectangle object that has the dimensions of the image.
# Update the position of this object by setting the values of rect.x and rect.y

self.rect = self.image.get_rect()
self.rect.y = 50
self.rect.x = 50

Upvotes: 0

Related Questions