当前位置:首页 » python教程 » 正文

python使用pygame创建精灵Sprite

看: 1344次  时间:2021-05-21  分类 : python教程

一 、精灵(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有如下定位属性:

    其中,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)

到此这篇关于python使用pygame创建精灵Sprite的文章就介绍到这了,更多相关python使用pygame创建Sprite内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

标签:pygame  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!