Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use specs::{Builder, Component, ReadStorage, System, VecStorage, World, WorldExt, RunNow, EntityBuilder};
- // =========================================================================================
- #[derive(Debug)]
- struct Position {
- x: f32,
- y: f32,
- }
- impl Component for Position {
- type Storage = VecStorage<Self>;
- }
- #[derive(Debug)]
- struct Velocity {
- x: f32,
- y: f32,
- }
- impl Component for Velocity {
- type Storage = VecStorage<Self>;
- }
- // =========================================================================================
- trait ComponentHandler{
- fn move_component_to<'a>(&mut self, builder: EntityBuilder<'a>) -> EntityBuilder<'a>;
- }
- struct ComponentHandlerImpl<T: Component> {
- pub component: Option<T>
- }
- impl<T: Component + Send + Sync> ComponentHandler for ComponentHandlerImpl<T> {
- fn move_component_to<'a>(&mut self, builder: EntityBuilder<'a>) -> EntityBuilder<'a> {
- if let Some(comp) = std::mem::replace(&mut self.component, None) {
- builder.with(comp)
- } else {
- builder
- }
- }
- }
- // =========================================================================================
- struct PrintPositionSystem;
- impl<'a> System<'a> for PrintPositionSystem {
- type SystemData = ReadStorage<'a, Position>;
- fn run(&mut self, position: Self::SystemData) {
- use specs::Join;
- for position in position.join() {
- println!("Hello, Pos {:?}", &position);
- }
- }
- }
- struct PrintVelocitySystem;
- impl<'a> System<'a> for PrintVelocitySystem {
- type SystemData = ReadStorage<'a, Velocity>;
- fn run(&mut self, velocity: Self::SystemData) {
- use specs::Join;
- for position in velocity.join() {
- println!("Hello, Vel {:?}", &position);
- }
- }
- }
- // =========================================================================================
- fn main() {
- let mut world = World::new();
- world.register::<Position>();
- world.register::<Velocity>();
- let mut vec: Vec<Box<dyn ComponentHandler>> = vec![
- Box::new(ComponentHandlerImpl { component: Some(Position { x: 1.0, y: 2.0 }) }),
- Box::new(ComponentHandlerImpl { component: Some(Velocity { x: 3.0, y: 4.0 }) }),
- ];
- for component_handler in vec.iter_mut() {
- component_handler.move_component_to(world.create_entity()).build();
- }
- let mut print_position_system = PrintPositionSystem;
- print_position_system.run_now(&world);
- let mut velocity_position_system = PrintVelocitySystem;
- velocity_position_system.run_now(&world);
- world.maintain();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement