summaryrefslogtreecommitdiffstats
path: root/src/physics.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/physics.rs')
-rw-r--r--src/physics.rs92
1 files changed, 49 insertions, 43 deletions
diff --git a/src/physics.rs b/src/physics.rs
index de09a2f..458f1e7 100644
--- a/src/physics.rs
+++ b/src/physics.rs
@@ -1,64 +1,70 @@
-use std::ops::Add;
+pub(crate) use error::{Error, Result};
+pub use point::Point;
+pub use vector::Vector;
-#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, Copy)]
-pub struct Point {
- pub x: u16,
- pub y: u16,
+mod error;
+mod point;
+mod vector;
+
+pub trait Physics {
+ fn tick_time<E: crate::Engine>(&mut self, engine: E) -> Result<()>;
+}
+
+pub trait Position {
+ fn get_position(&self) -> Point;
+ fn set_position<P: Into<Point>>(&mut self, position: P) -> Result<()>;
}
-impl Point {
- pub fn new(x: u16, y: u16) -> Self {
- Self { x, y }
+pub trait Velocity: Position {
+ fn get_velocity(&self) -> Vector;
+
+ fn set_velocity<V: Into<Vector>>(&mut self, velocity: V) -> Result<()>;
+
+ fn apply_velocity(&mut self) -> Result<()> {
+ self.set_position(self.get_position() + self.get_velocity())
}
- pub fn add_velocity(&mut self, velocity: Vector) {
- self.x += velocity.x;
- self.y += velocity.y;
+ fn reset_velocity(&mut self) -> Result<()> {
+ self.set_velocity(Vector::default())
}
}
-impl From<(u16, u16)> for Point {
- fn from((x, y): (u16, u16)) -> Self {
- Self { x, y }
- }
+pub trait Collider {
+ fn collision_map(&self) -> &Vec<Point>;
}
-impl From<Point> for (u16, u16) {
- fn from(point: Point) -> Self {
- (point.x, point.y)
+pub trait Collidable: Collider + Velocity {
+ fn next_collision_map(&self) -> Vec<Point> {
+ let velocity = self.get_velocity();
+ self.collision_map().iter().map(|p| *p + velocity).collect()
}
-}
-impl Add<Vector> for Point {
- type Output = Self;
+ fn check_collision<C: Collider>(&self, colliders: C) -> Result<()> {
+ let collision = self
+ .next_collision_map()
+ .iter()
+ .zip(colliders.collision_map())
+ .filter_map(|(p1, p2)| p1.eq(p2).then_some(*p1))
+ .collect::<Vec<point::Point>>();
- fn add(self, rhs: Vector) -> Self::Output {
- Self {
- x: self.x + rhs.x,
- y: self.y + rhs.y,
+ if !collision.is_empty() {
+ Ok(())
+ } else {
+ Err(Error::Collision(collision))
}
}
-}
-
-#[derive(Debug, Default, Clone, Copy)]
-pub struct Vector {
- pub x: u16,
- pub y: u16,
-}
-impl Vector {
- pub fn new(x: u16, y: u16) -> Self {
- Self { x, y }
+ fn check_colliders<C: Collider>(&self, colliders: Vec<C>) -> Result<()> {
+ for collidable in colliders {
+ self.check_collision(collidable)?
+ }
+ Ok(())
}
}
-impl Add<Vector> for Vector {
- type Output = Self;
-
- fn add(self, rhs: Vector) -> Self::Output {
- Self {
- x: self.x + rhs.x,
- y: self.y + rhs.y,
- }
+impl<T: Velocity + Collidable> Physics for T {
+ fn tick_time<E: crate::Engine>(&mut self, engine: E) -> Result<()> {
+ self.check_colliders(engine.get_colliders())?;
+ self.apply_velocity()
}
}