diff --git a/src/engine.rs b/src/engine.rs index 97b554e..dd6da21 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -195,6 +195,14 @@ impl<'context, 'game> Context<'context, 'game> { self.entities.push(Entity(id, components)); } + pub fn despawn(&mut self, entity_id: u64) { + *self.entities = self + .entities + .drain(..) + .filter(|v| v.0 != entity_id) + .collect(); + } + pub fn add_system(&mut self, system: Rc) { system.on_add(self); self.systems.push(system) diff --git a/src/main.rs b/src/main.rs index 902b05a..23280f2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,6 +46,39 @@ impl System for GravitySystem { } } +#[derive(Component)] +struct Cloud; + +struct CloudSystem; + +impl System for CloudSystem { + fn on_update(&self, ctx: &mut engine::Context, delta: f64) -> Result<(), engine::Error> { + let cloud_amount = ctx.entities_with_component::().len(); + if cloud_amount < 1 { + let cloud = ctx.load_sprite("textures/clouds.png").unwrap(); + ctx.spawn(vec![ + Box::new(Cloud), + Box::new(Sprite { sprite: cloud }), + Box::new(Position(-100.0, 150.0)), + Box::new(Velocity(0.0, 0.0)), + ]); + } + + for id in engine::Quwi::<(Cloud, Velocity)>::new().run(&ctx) { + let Velocity(x, _) = ctx.entity_component::(id); + *x = if *x < 200.0 { *x + 200.0 * delta } else { *x }; + } + + for id in engine::Quwi::<(Cloud, Position)>::new().run(&ctx) { + let Position(x, _) = ctx.entity_component::(id); + if *x > 1400.0 { + ctx.despawn(id); + } + } + Ok(()) + } +} + struct SpriteRenderer; impl System for SpriteRenderer { fn on_update(&self, ctx: &mut engine::Context, _delta: f64) -> Result<(), engine::Error> { @@ -89,9 +122,17 @@ fn main() { context.add_system(Rc::new(SpriteRenderer)); context.add_system(Rc::new(GravitySystem)); context.add_system(Rc::new(PlayerMovementSystem)); - let sprite = context.load_sprite("textures/player.png").unwrap(); + context.add_system(Rc::new(CloudSystem)); + let player = context.load_sprite("textures/player.png").unwrap(); + let background = context.load_sprite("textures/mountains.png").unwrap(); + context.spawn(vec![ - Box::new(Sprite { sprite }), + Box::new(Sprite { sprite: background }), + Box::new(Position(0.0, 0.0)), + ]); + + context.spawn(vec![ + Box::new(Sprite { sprite: player }), Box::new(Position(16.0, 500.0)), Box::new(Velocity(0.0, -600.0)), Box::new(Gravity), diff --git a/textures/clouds.png b/textures/clouds.png new file mode 100644 index 0000000..696bda7 Binary files /dev/null and b/textures/clouds.png differ diff --git a/textures/mountains.png b/textures/mountains.png new file mode 100644 index 0000000..2cbdc25 Binary files /dev/null and b/textures/mountains.png differ