我刚接触 Rust,并且正在使用 Piston 引擎制作游戏。
我想要用精灵表格渲染一系列实体,但是很多实体可能会共享一个精灵表格,因此我希望只加载和存储每个文件的一个副本。
伪代码中,我的方法基本上是这样的:
fn get_spritesheet(hashmap_cache, file):
if file not in hashmap_cache:
hashmap_cache[file] = load_image_file(file)
return hashmap_cache[file]
也许可以这样表达:
然后可能会有类似这样的内容:
//These 'sprite' fileds point to the same image in memory
let player1 = Entity { sprite: get_spritesheet(cache, "player.png") };
let player2 = Entity { sprite: get_spritesheet(cache, "player.png") };
然而,我在使用Rust的所有权系统时遇到了很多障碍(可能是因为我不理解它)。
据我所知,我希望cache/hashmap“拥有”图像资源。具体来说,返回引用(如
get_spritesheet函数中)似乎很奇怪。此外,一个结构体是否可以不拥有其所有成员?我认为可以,但我对如何实现感到困惑。