From a25d538cd6012b5eace96a410fc170afd21a7944 Mon Sep 17 00:00:00 2001 From: JMS <47158642+JMS55@users.noreply.github.com> Date: Wed, 8 May 2019 20:19:51 -0400 Subject: [PATCH] Update particles example to support multiple gravity centers based on mouse clicks --- examples/particles.rs | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/examples/particles.rs b/examples/particles.rs index 60664f7..7cbf8f2 100644 --- a/examples/particles.rs +++ b/examples/particles.rs @@ -23,7 +23,7 @@ fn main() -> Result<()> { struct Particles { particles: Vec, - gravity_center: Point, + gravity_centers: Vec, } impl Particles { @@ -45,7 +45,7 @@ impl Particles { Particles { particles, - gravity_center: Point::new(0.0, 0.0), + gravity_centers: Vec::new(), } }) } @@ -84,6 +84,10 @@ impl Game for Particles { input::Event::CursorMoved { x, y } => { input.cursor_position = Point::new(x, y); } + input::Event::MouseInput { + button: input::MouseButton::Left, + state: input::ButtonState::Released, + } => input.points_clicked.push(input.cursor_position), input::Event::KeyboardInput { key_code, state: input::ButtonState::Released, @@ -95,7 +99,9 @@ impl Game for Particles { } fn interact(&mut self, input: &mut Input, view: &mut View, _gpu: &mut Gpu) { - self.gravity_center = input.cursor_position; + for point in &input.points_clicked { + self.gravity_centers.push(*point); + } for key in &input.released_keys { match key { @@ -106,20 +112,23 @@ impl Game for Particles { } } + input.points_clicked.clear(); input.released_keys.clear(); } fn update(&mut self, _view: &View, _window: &Window) { - let gravity_center = self.gravity_center.clone(); + let gravity_centers = self.gravity_centers.clone(); // Update particles in parallel! <3 rayon self.particles.par_iter_mut().for_each(move |particle| { - let distance = particle.position - gravity_center; - - particle.acceleration = -((Self::G * Self::MASS) - * distance.normalize()) - / distance.norm_squared().max(1000.0); - + particle.acceleration = gravity_centers + .par_iter() + .map(|gravity_center| { + let distance = particle.position - gravity_center; + -((Self::G * Self::MASS) * distance.normalize()) + / distance.norm_squared().max(1000.0) + }) + .sum(); particle.velocity += particle.acceleration; particle.position += particle.velocity; }); @@ -287,6 +296,7 @@ impl View { struct Input { cursor_position: Point, + points_clicked: Vec, released_keys: Vec, } @@ -294,6 +304,7 @@ impl Input { fn new() -> Input { Input { cursor_position: Point::new(0.0, 0.0), + points_clicked: Vec::new(), released_keys: Vec::new(), } }