diff --git a/src/extensions/velocity.rs b/src/extensions/velocity.rs index 230f34c..de2c167 100644 --- a/src/extensions/velocity.rs +++ b/src/extensions/velocity.rs @@ -9,36 +9,58 @@ use crate::{ pub struct VelocityExtension; -impl Extension for VelocityExtension { - fn render(&self, _widget: &Arc) { - if let Some(velocity) = _widget.get::() { - if let Some(mut t) = _widget.get::() { - match &mut t.x { - Position::Const(x) => { - if velocity.0 > 0 { - *x += 1; - } else if velocity.0 < 0 { - *x -= 1; - } - } - _ => {} - } - - match &mut t.y { - Position::Const(y) => { - if velocity.1 > 0 { - *y += 1; - } else if velocity.1 < 0 { - *y -= 1; - } - } - _ => {} - } - - _widget.set_component(t); +impl VelocityExtension { + fn apply_velocity(ticks: u16, velocity: i32, x: &mut u16) { + if velocity.abs() != 0 && ticks as i32 % (1000 / velocity.abs()) == 0 { + if velocity > 0 { + *x += 1; + } else if velocity < 0 { + *x -= 1; } } } } +impl VelocityExtension { + fn apply_velocity_xy(ticks: u16, widget: &Arc) { + if let Some(velocity) = widget.get::() { + if let Some(mut t) = widget.get::() { + match &mut t.x { + Position::Const(x) => Self::apply_velocity(ticks, velocity.0, x), + _ => {} + } + + match &mut t.y { + Position::Const(y) => Self::apply_velocity(ticks, velocity.1, y), + _ => {} + } + + widget.set_component(t); + } + } + } +} + +impl Extension for VelocityExtension { + fn init(&self, widgets: &Vec>) { + std::thread::spawn({ + let widgets = widgets.clone(); + move || { + let mut tick = 0; + loop { + for widget in &widgets { + Self::apply_velocity_xy(tick, widget); + } + if tick > 1000 { + tick = 0; + } else { + tick += 1; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + }); + } +} + component!(Velocity(pub i32, pub i32)); diff --git a/src/main.rs b/src/main.rs index ec3e4eb..9de52a6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ fn main() { screen .draw(format!("Hello, World!")) .component(Transform::new()) - .component(Velocity(1, 0)) + .component(Velocity(100, 0)) .component(OnTick(|w| { if let Some(mut v) = w.get::() { if let Some(t) = w.get::() {