background stuff

This commit is contained in:
Theis Pieter Hollebeek 2024-04-10 09:25:36 +02:00
parent e29bb3e75a
commit 7aec7a36a7
4 changed files with 51 additions and 2 deletions

View File

@ -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<dyn System>) {
system.on_add(self);
self.systems.push(system)

View File

@ -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::<Cloud>().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::<Velocity>(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::<Position>(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),

BIN
textures/clouds.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 987 B

BIN
textures/mountains.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB