use bevy::{
ecs::component::{ComponentHooks, StorageType},
prelude::*,
};
use crate::{ecs::CommandsExt, event::OnScore, scoring::Score};
#[derive(Reflect)]
#[derive(Clone, Copy, PartialEq, Debug, Default)]
#[reflect(Component)]
pub struct Sum {
threshold: Score,
}
impl Sum {
pub fn new(threshold: impl Into<Score>) -> Self {
Self {
threshold: threshold.into(),
}
}
pub fn threshold(&self) -> Score {
self.threshold
}
pub fn set_threshold(&mut self, threshold: impl Into<Score>) {
self.threshold = threshold.into();
}
fn observer(trigger: Trigger<OnScore>, target: Query<(&Children, &Sum)>, mut scores: Query<&mut Score>) {
let Ok((children, settings)) = target.get(trigger.entity()) else {
return;
};
let mut sum: f32 = 0.;
for child_score in scores.iter_many(children) {
sum += child_score.get();
}
if sum < settings.threshold().get() {
sum = 0.;
}
let Ok(mut actor_score) = scores.get_mut(trigger.entity()) else {
return;
};
actor_score.set(sum);
}
}
impl Component for Sum {
const STORAGE_TYPE: StorageType = StorageType::Table;
fn register_component_hooks(hooks: &mut ComponentHooks) {
hooks.on_add(|mut world, _entity, _component| {
#[derive(Resource, Default)]
struct SumObserverSpawned;
world.commands().once::<SumObserverSpawned>().observe(Self::observer);
});
}
}