【问题标题】:how to create a circular sprite in pygame如何在pygame中创建一个圆形精灵
【发布时间】:2020-04-25 17:28:38
【问题描述】:

我尝试在 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

所以我一直在尝试不同的来源,但我似乎永远无法弄清楚如何去做。那么如何制作圆形精灵呢?它不需要移动或任何东西——我只需要一个小的(ish)精灵。

【问题讨论】:

  • 你检查the official documentation了吗? self.speed 是你发明的,但它应该是绘制坐标。
  • 当我尝试了官方文档方法@usr2564301它没有工作 - 通常官方文档让我感到困惑
  • 你觉得这很混乱吗? "center (tuple(int or float, int or float) or list(int or float, int or float) or Vector2(int or float, int or float)) - 圆的中心点作为2个整数的序列/浮动,例如(x,y)“它的哪一部分?它可能很简洁,但一切都在那里。

标签: python pygame sprite draw


【解决方案1】:

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 Wont Let Me Draw A Circle Error argument 3 must be sequence of length 2, not 4


此外,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()

注意,pygame.sprite.Sprite 对象的.rect.image 属性被.draw() 使用,pygame.sprite.Group 的方法用于绘制包含的精灵。

因此,可以通过更改矩形中编码的位置(例如self.rect.xself.rect.y)来移动精灵。

【讨论】:

  • 名称 x 未定义 - NameError: name 'x' is not defined
猜你喜欢
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 2019-08-07
相关资源
最近更新 更多