vec2.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. pub struct Vec2 {
  2. pub x: f64,
  3. pub y: f64
  4. }
  5. pub fn build_vec2(x: f64, y: f64) -> Vec2 {
  6. // Creates vector2.
  7. Vec2 {x: x, y: y}
  8. }
  9. impl Vec2 {
  10. pub fn abs(&mut self) {
  11. self.x = if self.x > 0f64 {self.x} else {-self.x};
  12. self.y = if self.y > 0f64 {self.y} else {-self.y};
  13. }
  14. pub fn distance_to(&self, other: &Vec2) -> f64 {
  15. // euclidean distance between two vectors.
  16. ((other.x - self.x).powf(2.0) + (other.y - self.y).powf(2.0)).sqrt()
  17. }
  18. pub fn dot_product(&self, other: &Vec2) -> f64 {
  19. // https://en.wikipedia.org/wiki/Dot_product
  20. self.x*other.x + self.y*other.y
  21. }
  22. pub fn length(&self) -> f64 {
  23. (self.x.powf(2.0) + self.y.powf(2.0)).sqrt()
  24. }
  25. pub fn normalized(&self) -> Vec2 {
  26. let l = self.length();
  27. if l != 0.0 {
  28. return Vec2 {
  29. x: self.x / l,
  30. y: self.y / l
  31. }
  32. }
  33. Vec2 {x: 0.0, y: 0.0}
  34. }
  35. }
  36. impl std::fmt::Display for Vec2 {
  37. // Provides vector2 string representation.
  38. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  39. write!(f, "Vec2({}, {})", self.x, self.y)
  40. }
  41. }
  42. // Overload operators
  43. impl std::ops::Add for &Vec2 {
  44. // Provides vectors addition.
  45. type Output = Vec2;
  46. fn add(self, other: &Vec2) -> Vec2 {
  47. Vec2 {x: self.x + other.x, y: self.y + other.y}
  48. }
  49. }
  50. impl std::ops::Sub for &Vec2 {
  51. // Provides vectors substraction.
  52. type Output = Vec2;
  53. fn sub(self, other: &Vec2) -> Vec2 {
  54. Vec2 {x: self.x - other.x, y: self.y - other.y}
  55. }
  56. }
  57. impl std::ops::Mul for &Vec2 {
  58. // Provides vectors multiplication.
  59. type Output = Vec2;
  60. fn mul(self, other: &Vec2) -> Vec2 {
  61. Vec2 {x: self.x * other.x, y: self.y * other.y}
  62. }
  63. }