From 92787d379ad61bc3ffc80d4944b5f19385deebff Mon Sep 17 00:00:00 2001 From: =?utf8?q?Tomas=20Wenstr=C3=B6m?= Date: Sun, 14 Feb 2021 20:56:02 +0100 Subject: [PATCH] Collide with the walls instead of the grid --- src/core/game.rs | 51 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 20 deletions(-) diff --git a/src/core/game.rs b/src/core/game.rs index 3a8d3c9..5c1bda8 100644 --- a/src/core/game.rs +++ b/src/core/game.rs @@ -162,6 +162,7 @@ pub struct Character { ctrl: Rc>, pos: Point, vel: Point, + standing_on: Option, } impl Character { @@ -170,6 +171,7 @@ impl Character { ctrl, pos: point!(300.0, 300.0), vel: point!(0.0, 0.0), + standing_on: None, } } } @@ -178,23 +180,38 @@ impl Object for Character { fn update(&mut self, objects: &mut Objects, lvl: &Level, dt: Duration) -> ObjectState { let ctrl = self.ctrl.borrow(); - let x = (self.pos.x / lvl.grid.scale.width as f64).min(lvl.grid.size.width as f64 - 1.0).max(0.0) as usize; - let y = (self.pos.y / lvl.grid.scale.height as f64).min(lvl.grid.size.height as f64 - 1.0).max(0.0) as usize; - self.vel += lvl.gravity; - if lvl.grid.cells[x][y] { - if self.vel.y > 0.0 && !(ctrl.mov.down() && ctrl.jump.is_pressed) { - self.vel.y = 0.0; - self.vel.x *= 0.9; - self.pos.y -= 1.0; - } - - if !ctrl.mov.down() { + match &self.standing_on { + Some(wall) => { if ctrl.jump.is_pressed && !ctrl.jump.was_pressed { - self.vel.y = -5.0; + if ctrl.mov.to_point().length() < 0.1 { + self.vel = wall.normal().into(); + } else { + self.vel = ctrl.mov.to_point(); + } + self.vel *= 5.0; + self.pos += self.vel * 0.1; + self.standing_on = None; + } else { + self.vel *= 0.9; + } + }, + None => { + self.vel += lvl.gravity; + self.pos += self.vel; + + match ctrl.mov.x { + v if v < -0.9 && self.vel.x > -5.0 => { self.vel.x -= 0.5 } + v if v > 0.9 && self.vel.x < 5.0 => { self.vel.x += 0.5 } + _ => {} + } + + if let Intersection(wall, pos) = lvl.intersect_walls(self.pos - self.vel, self.pos) { + self.standing_on = Some(wall); + self.pos = pos; + self.vel = point!(0.0, 0.0); } } } - self.pos += self.vel; if ctrl.shoot.is_pressed { use rand::distributions::{Distribution, Normal}; @@ -202,7 +219,7 @@ impl Object for Character { let direction = if ctrl.aim.to_point().length() > 0.1 { ctrl.aim.to_point() } else { ctrl.mov.to_point() }; for _i in 0..100 { objects.push(Box::new(Boll { - pos: self.pos, + pos: self.pos + point!(0.0, -16.0), // half the height of mario vel: direction * (10.0 + rand::random::()) + point!(normal.sample(&mut rand::thread_rng()), normal.sample(&mut rand::thread_rng())) + self.vel, bounces: 2, })); @@ -223,12 +240,6 @@ impl Object for Character { }; } - match ctrl.mov.x { - v if v < -0.9 && self.vel.x > -5.0 => { self.vel.x -= 0.5 } - v if v > 0.9 && self.vel.x < 5.0 => { self.vel.x += 0.5 } - _ => {} - } - Alive } -- 2.11.0