使用Sprite和SpriteList绘制#
精灵是什么?#
每个精灵都描述了游戏对象的位置以及如何绘制它。这包括:
它在世界上的什么位置
在哪里可以找到图像数据
图像应该有多大
本页的其余部分将使用 SpriteList
类将精灵绘制到屏幕上。
为什么是SpriteList?#
它们就是硬件的工作原理#
图形硬件被设计为同时绘制多组对象。这些团体被称为 batches 。
每个 SpriteList
自动转换为 Sprite
放到一个优化的批次中。一批精灵有一个或数百个精灵并不重要:绘制仍然需要相同的时间!
这意味着使用较少的批次有助于您的游戏运行得更快,并且您应该避免尝试一次绘制一个精灵。
它们有助于更快地开发游戏#
精灵的作用不仅仅是吸引眼球。它们还具有可为您节省时间和精力的内置功能,包括:
自动跳过屏幕外的精灵
碰撞检测
调试命中框的绘图
使用Sprite和SpriteList#
让我们来看看示例代码。
使用精灵列表绘制精灵需要3个步骤:
创建
SpriteList
创建并附加您的
Sprite
实例(S)添加到列表
下面是一个最小的例子:
sprite_minimal.py#
1"""
2Minimal Sprite Example
3
4Draws a single sprite in the middle screen.
5
6If Python and Arcade are installed, this example can be run from the command line with:
7python -m arcade.examples.sprite_minimal
8"""
9import arcade
10
11
12class WhiteSpriteCircleExample(arcade.Window):
13
14 def __init__(self):
15 super().__init__(800, 600, "White SpriteCircle Example")
16 self.sprites = None
17 self.setup()
18
19 def setup(self):
20 # 1. Create the SpriteList
21 self.sprites = arcade.SpriteList()
22
23 # 2. Create & append your Sprite instance to the SpriteList
24 self.circle = arcade.SpriteCircle(30, arcade.color.WHITE) # 30 pixel radius circle
25 self.circle.position = self.width // 2, self.height // 2 # Put it in the middle
26 self.sprites.append(self.circle) # Append the instance to the SpriteList
27
28 def on_draw(self):
29 # 3. Call draw() on the SpriteList inside an on_draw() method
30 self.sprites.draw()
31
32
33def main():
34 game = WhiteSpriteCircleExample()
35 game.run()
36
37
38if __name__ == "__main__":
39 main()
将图像与精灵一起使用#
初学者应该查看以下内容以了解更多信息,例如如何将图像加载到精灵中:
视区、摄影机和屏幕#
中级用户可以克服以下限制 arcade.Window
具有以下类:
arcade.Camera
(examples) to control which part of game space is drawnarcade.View
(examples) for start, end, and menu screens