refactor: Changed BpmTimer into Resource

This commit is contained in:
Alexey 2026-04-20 15:14:40 +03:00
commit f3b2d0313e
5 changed files with 11 additions and 30 deletions

View file

@ -40,7 +40,6 @@ pub const GROUP_ATTACK: Group = Group::GROUP_5;
/// Temporary function to setup world
pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Player::bundle(&asset_server, Vec2::ZERO));
commands.spawn(BpmTimer::new(120.));
}
/// Test function to setup [AnimatedSprite]

View file

@ -26,13 +26,8 @@ pub fn handle_input(
Option<&mut states::Awaiting>,
)>,
timer_query: Query<&BpmTimer>,
timer: Res<BpmTimer>,
) {
let Some(timer) = timer_query.iter().next() else {
error!("No BpmTimer provided");
return;
};
let bpm = timer.get_bpm();
for (

View file

@ -43,8 +43,8 @@ pub fn from_awaiting_to_choosing(trans: Trans<Awaiting, PlayerInput>) -> Choosin
}
/// Trigger that returns [BpmTimer]'s bpm
pub fn get_timer_bpm(query: Query<&BpmTimer>) -> Option<f32> {
query.iter().next().map(|t| t.get_bpm())
pub fn get_timer_bpm(timer: Res<BpmTimer>) -> Option<f32> {
Some(timer.get_bpm())
}
/// Transition from [Attacking] to [Awaiting]

View file

@ -23,6 +23,7 @@ impl Plugin for GamePlugin {
StateMachinePlugin::default(),
))
.insert_resource(BpmTimer::new(120.))
.add_systems(Startup, (
setup,
setup_animated_sprite,
@ -31,7 +32,7 @@ impl Plugin for GamePlugin {
anim::sprite::update_animated_sprites,
combat::attack::update_attack_areas,
player::systems::handle_input,
timer::update_bpm_timers,
timer::update_bpm_timer,
))
.register_component_as::<dyn Weapon, knife::Knife>();
}

View file

@ -16,20 +16,10 @@ pub fn bpm_from_duration(dur: Duration) -> f32 {
60_000. / (dur.as_millis() as f32)
}
/// Event that is triggered when [BpmTimer] just ticked
#[derive(EntityEvent, Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Event, Clone, PartialEq, Debug)]
pub struct TickEvent {
/// [BpmTimer] that triggered event
#[event_target] pub timer: Entity,
/// Total elapsed time of that timer in beats
pub elapsed: f32,
}
/// Timer that is based on beats per minute (BPM) value
/// Ticks every beat, counts total ticks and triggers [TickEvent]
#[derive(Component, Clone, PartialEq, Debug, Reflect)]
#[reflect(Component, Clone, PartialEq, Debug)]
/// Ticks every beat and counts total ticks
#[derive(Resource, Clone, PartialEq, Debug, Reflect)]
#[reflect(Resource, Clone, PartialEq, Debug)]
pub struct BpmTimer {
timer: Timer,
elapsed: f32,
@ -80,11 +70,7 @@ impl BpmTimer {
}
}
/// System that ticks each [BpmTimer] and triggers [TickEvent]s
pub fn update_bpm_timers(mut commands: Commands, time: Res<Time>, timers: Query<(Entity, &mut BpmTimer)>) {
for (timer_id, mut timer) in timers {
if timer.tick(time.delta()) {
commands.trigger(TickEvent { timer: timer_id, elapsed: timer.beats_elapsed() });
}
}
/// System that ticks [BpmTimer]
pub fn update_bpm_timer(time: Res<Time>, mut timer: ResMut<BpmTimer>) {
timer.tick(time.delta());
}