Как создать круговой спрайт в Pygame - PullRequest
1 голос
/ 25 апреля 2020

Я пытался сделать круговой спрайт в Pygame. Мой класс спрайтов:

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)

Это возвращает ошибку:

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

, поэтому я пробовал разные источники, но я никогда не мог понять, как сделай это. Так как сделать круговой спрайт? Ему не нужно ни двигаться, ни что-либо - мне нужен маленький (i sh) спрайт.

1 Ответ

1 голос
/ 25 апреля 2020

3-й аргумент pygame.draw.circle() должен быть кортежем из 2 компонентов, координаты x и y которого совпадают по кругу:

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

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

В приведенном выше примере (self.width//2, self.height//2) является центром круга, а 5 является радиусом (в пикселях).


Кроме того pygame.sprite.Sprite объект всегда должен иметь атрибут .rect (экземпляр 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()

Обратите внимание, атрибут .rect и .image атрибута * Объект 1029 * используется .draw(), методом pygame.sprite.Group для рисования содержащихся спрайтов.

Таким образом, спрайт можно перемещать, изменяя позиция (например, self.rect.x, self.rect.y), закодированная в прямоугольнике.

...