Calculations from the world's 2D to the wall's 1D
[kaka/rust-sdl-test.git] / src / core / level / mod.rs
index bdc6cb0..e422042 100644 (file)
@@ -106,7 +106,7 @@ impl Level {
            for e in &wall.edges {
                if !debug_mode {
                    let c = (e.p1 + e.p2) / 2.0;
-                   let a = (e.p2 - e.p1).to_angle() - std::f64::consts::FRAC_PI_2.radians();
+                   let a = e.normal().reverse();
 
                    renderer.draw_line(
                        <(i32, i32)>::from(c.to_i32()),
@@ -250,6 +250,15 @@ impl WallEdge {
        let cross = (self.p2 - self.p1).cross_product(p - self.p1);
        cross > 0.0
     }
+
+    fn normal(&self) -> Angle {
+       self.angle() + std::f64::consts::FRAC_PI_2.radians()
+    }
+
+    /// Angle from the right to the left point if the normal is up.
+    fn angle(&self) -> Angle {
+       (self.p2 - self.p1).to_angle()
+    }
 }
 
 ////////// WALL ////////////////////////////////////////////////////////////////
@@ -277,6 +286,32 @@ impl Wall {
     }
 
     pub fn normal(&self) -> Angle {
-       (self.edge.p2 - self.edge.p1).to_angle() + std::f64::consts::FRAC_PI_2.radians()
+       self.edge.normal()
+    }
+
+    pub fn angle(&self) -> Angle {
+       self.edge.angle()
+    }
+
+    pub fn from_2d(&self, pos: &Point<f64>, vel: &Point<f64>) -> (f64, f64) {
+       let pos = self.projection_of(*pos - self.edge.p1);
+       let vel = self.projection_of(*vel);
+       (pos, vel)
+    }
+
+    pub fn to_2d(&self, pos: f64, vel: f64) -> (Point<f64>, Point<f64>) {
+       let a = Point::from(self.edge.angle());
+       let pos = self.edge.p1 + a * pos;
+       let vel = a * vel;
+       (pos, vel)
+    }
+
+    /// Returns the 1D position of a point projected onto this wall.
+    /// This is done by rotating the point using a rotation matrix and then taking the resulting x value.
+    /// x'=xcos−ysin <- only this is used
+    /// y'=xsin+ycos
+    fn projection_of(&self, p: Point<f64>) -> f64 {
+       let r = Point::from(self.edge.angle());
+       p.x * r.x + p.y * r.y // r.y is inverted here instead of inverting the angle
     }
 }