Character states - first draft
authorTomas Wenström <tomas.wenstrom@gmail.com>
Sun, 28 Feb 2021 16:20:51 +0000 (17:20 +0100)
committerTomas Wenström <tomas.wenstrom@gmail.com>
Sun, 28 Feb 2021 16:20:51 +0000 (17:20 +0100)
src/core/object/character.rs

index 8632ee2..18cb0aa 100644 (file)
@@ -11,22 +11,52 @@ use std::cell::RefCell;
 use std::rc::Rc;
 use time::Duration;
 
+////////// STATE ///////////////////////////////////////////////////////////////
+
+trait State {
+    fn enter(&self) {}
+    fn exit(&self) {}
+    fn update(&mut self, body: &mut Body, ctrl: &Controller, objects: &mut Objects, lvl: &Level, dt: Duration) -> Option<Box<dyn State>>;
+}
+
 ////////// CHARACTER ///////////////////////////////////////////////////////////
 
+struct Body {
+    pub pos: Point<f64>,
+    pub vel: Point<f64>,
+    pub standing_on: Option<Wall>,
+}
+
+struct StateHolder(Box<dyn State>);
+
+impl StateHolder {
+    pub fn get(&mut self) -> &mut Box<dyn State> {
+       &mut self.0
+    }
+
+    pub fn set(&mut self, state: Box<dyn State>) {
+       self.0.exit();
+       self.0 = state;
+       self.0.enter();
+    }
+}
+
 pub struct Character {
     ctrl: Rc<RefCell<Controller>>,
-    pos: Point<f64>,
-    vel: Point<f64>,
-    standing_on: Option<Wall>,
+    body: Body,
+    state: StateHolder, // Plays well with the borrow checker
 }
 
 impl Character {
     pub fn new(ctrl: Rc<RefCell<Controller>>) -> Self {
        Character {
            ctrl,
-           pos: point!(300.0, 300.0),
-           vel: point!(0.0, 0.0),
-           standing_on: None,
+           body: Body {
+               pos: point!(300.0, 300.0),
+               vel: point!(0.0, 0.0),
+               standing_on: None,
+           },
+           state: StateHolder(Box::new(FallState)),
        }
     }
 }
@@ -35,35 +65,19 @@ impl Object for Character {
     fn update(&mut self, objects: &mut Objects, lvl: &Level, dt: Duration) -> ObjectState {
        let ctrl = self.ctrl.borrow();
 
-       match &self.standing_on {
-           Some(wall) => {
-               if ctrl.jump.is_pressed && !ctrl.jump.was_pressed {
-                   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 Some(state) = self.state.get().update(&mut self.body, &ctrl, objects, lvl, dt) {
+           self.state.set(state);
+       }
 
-               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);
+       match &self.body.standing_on {
+           Some(_wall) => {
+           },
+           None => { // in air
+               if let Intersection(wall, pos) = lvl.intersect_walls(self.body.pos - self.body.vel, self.body.pos) {
+                   self.body.standing_on = Some(wall);
+                   self.body.pos = pos;
+                   self.body.vel = point!(0.0, 0.0);
+                   self.state.set(Box::new(StandState));
                }
            }
        }
@@ -74,13 +88,13 @@ 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::new(
-                   self.pos + point!(0.0, -16.0), // half the height of mario
-                   direction * (10.0 + rand::random::<f64>()) + point!(normal.sample(&mut rand::thread_rng()), normal.sample(&mut rand::thread_rng())) + self.vel,
+                   self.body.pos + point!(0.0, -16.0), // half the height of mario
+                   direction * (10.0 + rand::random::<f64>()) + point!(normal.sample(&mut rand::thread_rng()), normal.sample(&mut rand::thread_rng())) + self.body.vel,
                    2,
                )));
            }
            ctrl.rumble(1.0, dt);
-           self.vel -= direction * 0.1;
+           self.body.vel -= direction * 0.1;
        }
 
        ObjectState::Alive
@@ -89,24 +103,24 @@ impl Object for Character {
     fn render(&self, renderer: &mut Renderer, sprites: &SpriteManager) {
         let block = sprites.get("mario");
        let size = 32;
-        renderer.blit(block, None, Rect::new(self.pos.x as i32 - size as i32 / 2, self.pos.y as i32 - size as i32, size, size));
+        renderer.blit(block, None, Rect::new(self.body.pos.x as i32 - size as i32 / 2, self.body.pos.y as i32 - size as i32, size, size));
 
        let ctrl = &self.ctrl.borrow();
        let l = 300.0;
-       let pos = (self.pos.x as i32, self.pos.y as i32);
+       let pos = (self.body.pos.x as i32, self.body.pos.y as i32);
        // // axis values
-       // let p = (self.pos + ctrl.aim.to_axis_point() * l).to_i32().into();
+       // let p = (self.body.pos + ctrl.aim.to_axis_point() * l).to_i32().into();
        // renderer.draw_line(pos, p, (0, 255, 0));
        // draw_cross(renderer, p);
        // values limited to unit vector
-       let p = (self.pos + ctrl.aim.to_point() * l).to_i32().into();
+       let p = (self.body.pos + ctrl.aim.to_point() * l).to_i32().into();
        renderer.draw_line(pos, p, (255, 0, 0));
        draw_cross(renderer, p);
-       let p = (self.pos + ctrl.mov.to_point() * l).to_i32().into();
+       let p = (self.body.pos + ctrl.mov.to_point() * l).to_i32().into();
        renderer.draw_line(pos, p, (0, 255, 0));
        draw_cross(renderer, p);
        // // circle values
-       // let p = (self.pos + Point::from(ctrl.aim.a) * l).to_i32().into();
+       // let p = (self.body.pos + Point::from(ctrl.aim.a) * l).to_i32().into();
        // renderer.draw_line(pos, p, (0, 0, 255));
        // draw_cross(renderer, p);
     }
@@ -116,3 +130,48 @@ fn draw_cross(renderer: &mut Renderer, p: (i32, i32)) {
     renderer.canvas().draw_line((p.0 - 5, p.1), (p.0 + 5, p.1)).unwrap();
     renderer.canvas().draw_line((p.0, p.1 - 5), (p.0, p.1 + 5)).unwrap();
 }
+
+////////// FALLING /////////////////////////////////////////////////////////////
+
+struct FallState;
+
+impl State for FallState {
+    fn update(&mut self, body: &mut Body, ctrl: &Controller, _objects: &mut Objects, lvl: &Level, _dt: Duration) -> Option<Box<dyn State>> {
+       body.vel += lvl.gravity;
+       body.pos += body.vel;
+
+       match ctrl.mov.x {
+           v if v < -0.9 && body.vel.x > -5.0 => { body.vel.x -= 0.5 }
+           v if v > 0.9 && body.vel.x < 5.0 => { body.vel.x += 0.5 }
+           _ => {}
+       }
+
+       None
+    }
+}
+
+////////// STANDING /////////////////////////////////////////////////////////////
+
+struct StandState;
+
+impl State for StandState {
+    fn update(&mut self, body: &mut Body, ctrl: &Controller, _objects: &mut Objects, _lvl: &Level, _dt: Duration) -> Option<Box<dyn State>> {
+       if let Some(wall) = &body.standing_on {
+           if ctrl.jump.is_pressed && !ctrl.jump.was_pressed {
+               if ctrl.mov.to_point().length() < 0.1 {
+                   body.vel = wall.normal().into();
+               } else {
+                   body.vel = ctrl.mov.to_point();
+               }
+               body.vel *= 5.0;
+               body.pos += body.vel * 0.1;
+               body.standing_on = None;
+               return Some(Box::new(FallState))
+           } else {
+               body.vel *= 0.9;
+           }
+       }
+
+       None
+    }
+}