...

/

Data-driven Spawning

Data-driven Spawning

Learn about data-driven spawning.

Spawning data-driven entities is the process of reading the game definition data. Outputting an in-game object like a health potion begins as a data template and awaits discovery on the map:

Let’s create a new function, implemented as part of the Template. First, start with the function signature:

Press + to interact
impl Templates {
pub fn load() -> Self {
let file = File::open("resources/template.ron")
.expect("Failed opening file");
from_reader(file).expect("Unable to load templates")
}
pub fn spawn_entities(
&self,
ecs: &mut World,
rng: &mut RandomNumberGenerator,
level: usize,
spawn_points: &[Point]
) {

The parameters for this function align closely with the spawning functions we already have in mod.rs. We take a borrowed reference to the ECS world and the RandomNumberGenerator. Note which game level we’re creating and store a list of locations in which we can spawn entities.

The next section builds a spawn table for the current level. Add the following code to our new function:

Press + to interact
let mut available_entities = Vec::new();
self.entities
.iter()
.filter(|e| e.levels.contains(&level))
.for_each(|t| {
for _ in 0 .. t.frequency {
available_entities.push(t);
}
}
);
  • Line 1: Create a mutable vector in which we’ll store a list of entities that may be spawned on this level.

  • Line 3: Iterate the list of entity templates we loaded in the constructor.

  • Line 4: Use filter to include only entities whose levels list includes the current level.

  • Line 6: Here’s the for loop to add each available entity a number of times equal to the entry’s frequency.

The available_entities list contains references to members of the entities collection. Rather than duplicating each entry, we store a pointer to the original, saving a lot of memory. Each possible entity appears a number of times in the ...