2022-08-01 13:58:07 +00:00
|
|
|
#[derive(Copy, Clone, PartialEq, Debug, Default, derive_more::Sub)]
|
2022-07-29 13:49:16 +00:00
|
|
|
pub struct Vector {
|
|
|
|
pub x: f32,
|
|
|
|
pub y: f32,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Vector {
|
|
|
|
pub fn new(x: f32, y: f32) -> Self {
|
|
|
|
Self { x, y }
|
|
|
|
}
|
|
|
|
|
2022-08-01 10:48:24 +00:00
|
|
|
pub fn from_terminal(x: u16, y: u16) -> Self {
|
|
|
|
Vector::new(x as f32, y as f32 * 2.0)
|
|
|
|
}
|
|
|
|
|
2022-07-29 13:49:16 +00:00
|
|
|
pub fn len(&self) -> f32 {
|
|
|
|
(self.x * self.x + self.y * self.y).sqrt()
|
|
|
|
}
|
|
|
|
|
2022-07-29 14:50:27 +00:00
|
|
|
pub fn abs(&self) -> Vector {
|
|
|
|
Self::new(self.x.abs(), self.y.abs())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn sum(&self) -> f32 {
|
|
|
|
self.x + self.y
|
|
|
|
}
|
|
|
|
|
2022-07-29 13:49:16 +00:00
|
|
|
pub fn center(&self) -> Vector {
|
|
|
|
Self::new(self.x / 2.0, self.y / 2.0)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn angle(&self) -> f32 {
|
|
|
|
self.y.atan2(self.x)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
use approx::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn new() {
|
|
|
|
let v = Vector::new(4.0, 7.0);
|
|
|
|
assert_eq!(4.0, v.x);
|
|
|
|
assert_eq!(7.0, v.y);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn len() {
|
|
|
|
assert_abs_diff_eq!(8.5, Vector::new(3.0, 8.0).len(), epsilon = 0.1);
|
|
|
|
}
|
|
|
|
|
2022-07-29 14:50:27 +00:00
|
|
|
#[test]
|
|
|
|
fn abs() {
|
|
|
|
assert_eq!(Vector::new(3.0, 7.0), Vector::new(-3.0, -7.0).abs());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn sum() {
|
|
|
|
assert_eq!(11.0, Vector::new(3.0, 8.0).sum());
|
|
|
|
}
|
|
|
|
|
2022-07-29 13:49:16 +00:00
|
|
|
#[test]
|
|
|
|
fn center() {
|
|
|
|
assert_eq!(Vector::new(4.0, 9.0), Vector::new(8.0, 18.0).center());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn angle() {
|
|
|
|
assert_abs_diff_eq!(-1.5, Vector::new(2.0, -20.0).angle(), epsilon = 0.1);
|
|
|
|
}
|
|
|
|
}
|