这是this question的后续:
注意:这是在python中,使用pygame库。在
我想澄清一下这个声明,这是对上述问题的评论:
Another important thing, don't use the same Sprite() nor the same Rectangle in different locations. If you want to draw another copy of the same image in a new location make a copy of the rectangle, then create a new Sprite() object.
我有一组游戏资产,我想随机挑选一个来添加我的 精灵小组。我目前正在这样做:
class TestSprite(pygame.sprite.Sprite):
def __init__(self, strFolder):
super(TestSprite, self).__init__()
self.image = load_image(strFolder + 'x.png'))
#....
def GetRandomAsset():
rnd = random.randrange(1, 4)
if rnd == 1:
return TestSprite('assets/A/')
elif rnd == 2:
return TestSprite('assets/B/')
elif rnd == 3:
return TestSprite('assets/C/')
else:
return TestSprite('assets/D/')
#....
my_group = pygame.sprite.Group()
my_group.add(GetRandomAsset())
#.....
#Control FPS
#Check Events
#Update State
#Clear Screen
#Draw Current State
#Update Display
一切都按预期工作;每次我运行上述代码时,屏幕上都会显示一个新的精灵。我的问题是每次我添加一个精灵,我必须从磁盘加载它,即使我使用相同的4图像一遍又一遍。在
我想把我所有的资产存储在一个名为preloadassets的全局列表中会更明智。那么每当我需要的时候就去做:my_group.add(PRELOADEDASSETS[x])
但当我试图这么做的时候,我只能拥有我的每一份资产的副本。在
如何预加载所有资产,然后在需要时获取存储的数据?在
谢谢!在
在这种情况下,这是一个有效的建议。当然,将一个曲面多次blit到不同的位置(例如使用不同的
Rect
)当然没有问题,但是如果使用Group
来处理/简化绘图,则需要为每个要绘制图像的位置提供一个对象。在要回答您的实际问题:
您不需要缓存
Sprite
实例。只需缓存Surface
实例。在这样,您可以使用不同的
Sprite
对象将同一图像绘制到不同的位置。在简单的缓存实现可以如下所示:
这将预先加载所有图像(可能是您想要的,也可能不是您想要的);添加惰性很容易,但您可能不希望出现延迟(什么是最好的取决于实际加载多少图像以及何时加载)。在
你甚至可以浏览游戏目录中的所有文件夹,自动检测并加载所有图像,但这种疯狂行为不在这个范围之内。在
相关问题 更多 >
编程相关推荐