itstwalker
itstwalker

Reputation: 53

OOP Pygame Circle

I am creating a game and I need a ring created around the character. I have OOP written for creating a wall, seen below but I don't know how to adapt this code so that it can create a ring around my player.

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x

Also, variables I want to pass in are the colour, radius, width/thickness and x & y coordinates, e.g.

circle = Circle(colour, radius, width, x, y)

Drawing sprites edit:

spriteList.add(wallList)
spriteList.draw(screen)

Any help greatly appreciated, Cheers

Upvotes: 0

Views: 891

Answers (1)

Rabbid76
Rabbid76

Reputation: 210948

A circle can be drawn with pygame.draw.circle

pygame.draw.circle(surface, color, center, radius)

If you just want to draw a circular sprite, all you need to do is specify the radius and width (line thickness) of the circle:

class Circle(pygame.sprite.Sprite):

    def __init__(self, circleColor, radius, width, x, y):
        super().__init__()
        
        self.image = pygame.Surface((radius * 2, radius * 2), pygame.SRCALPHA)
        pygame.draw.circle(self.image, circleColor, (radius, radius), radius, width)
        self.rect = self.image.get_rect(center = (x, y))

With this solution, you need to draw 2 objects, the sprite and the circle, separately at the same position.

However, if you want to create a single sprite object with a circle around it, you need to create a transparent surface that is larger than the sprite image. blit the sprite on the surface and draw a circle around it. In the following image is a pygame.Surface object:

import math
class MyPlayer(pygame.sprite.Sprite):

    def __init__(self, x, y, image, circleColor, width):
        super().__init__()
        
        diameter = math.hypot(*image.get_size())
        radius = diameter // 2

        self.image = pygame.Surface((diameter, diameter), pygame.SRCALPHA)
        self.image.blit(image, image.get_rect(center = (radius, radius))
        pygame.draw.circle(self.image, circleColor, (radius, radius), radius, width)
        self.rect = self.image.get_rect(center = (x, y))

Upvotes: 1

Related Questions