一 、精灵(Sprite),屏幕上的对象。精灵组是精灵的组合。创建空的精灵组对象:

精灵组可以对其中的所有精灵调用它们各自的更新方法(self.update)来进行更新,如位置更新、碰撞检测、冲突检测等:

all_sprites.update()

    精灵组可以对其中的所有精灵调用它们各自的DRAW方法(self.update)来绘制精灵:

all_sprites.draw(screen)

二、创建精灵

    1、创建精灵需要继承基类pg.sprite.Sprite。每个Pygame精灵都必须拥有两个属性: image和 rect

class Player(pg.sprite.Sprite):
	def __init__(self):
		pg.sprite.Sprite.__init__(self)
		self.img = pg.Surface((50, 50))
		self.img.fill(GREEN)
		self.rect = self.img.get_rect()
		self.rect.center = (215, 215)

    其中,rect有如下定位属性:

python使用pygame创建精灵Sprite

    其中,topleft, topright, center, bottomleft, bottomright为二元int元组,其余的为int。

    2、添加update方法:

def update(self):
	self.rect.x += 5
	if self.rect.left > WIDTH:
		self.rect.right = 0

    在游戏循环中,有all_sprites.update()。这意味着对于组中的每个sprite,Pygame将查找一个update()函数并运行它。

三、将精灵加入精灵组:

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。