Skip to content

Creating Systems

Ethan Almloff edited this page Apr 7, 2024 · 1 revision

This wiki page is about creating systems to act upon your entities and components. There are currently two ways to do this: the easy single-threaded way, and the more complicated multithreaded way.

The Single Threaded Way

struct MySingleThreadedSystem {}

impl System for MovementSystem {
    fn run(&mut self, engine: &mut EntitiesAndComponents) {
        for i in 0..engine.entities.len() {
            // This will never panic in this case because entities are never removed
            // but be careful when doing this otherwise
            let entity = engine.get_nth_entity(i).unwrap();

            // Get the position and velocity components.
            // If you aren't sure if the components are on the entity use try_get_components_mut instead
            let (position, velocity) =
                engine.get_components_mut::<(Position, Velocity)>(entity);

            position.x += velocity.x;
            position.y += velocity.y;

            println!("Position: {}, {}", position.x, position.y);
        }
    }
}

The Multi-Threaded Way

struct ParallelMovementSystem {}

impl System for ParallelMovementSystem {
    fn prestep(&mut self, engine: &EntitiesAndComponents) {
        // Do anything you need to do before the single_entity_step function is called
        // You can store anything in self
    }

    // Only do this if you implement the prestep function
    fn implements_prestep(&self) -> bool {
        true
    }

    fn single_entity_step(&self, single_entity: &mut SingleMutEntity) {
        let (position, velocity) = single_entity.get_components_mut::<(Position, Velocity)>();

        position.x += velocity.x;
        position.y += velocity.y;

        println!("Position: {}, {}", position.x, position.y);
    }

    // Only do this if you implement the single_entity_step function
    fn implements_single_entity_step(&self) -> bool {
        true
    }
}

Clone this wiki locally