vec2.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * 2D Physic Engine
  3. * vec2.h: Definition and implementation of the 2D vector
  4. * Based on pikuma.com Learn Game Physics Engine Programming course.
  5. * Copyright (c) 2022 986-Studio. All Right Reserved
  6. *
  7. * Created by Manoël Trapier on 07/06/2022.
  8. */
  9. #ifndef PHYSICENGINE_VEC2_H
  10. #define PHYSICENGINE_VEC2_H
  11. #include <cmath>
  12. struct vec2
  13. {
  14. double x, y;
  15. vec2() : x(0.0), y(0.0) {};
  16. vec2(double x, double y) : x(x), y(y) {};
  17. ~vec2() = default;
  18. void add(const vec2 &v)
  19. {
  20. this->x += v.x;
  21. this->y += v.y;
  22. };
  23. void sub(const vec2 &v)
  24. {
  25. this->x -= v.x;
  26. this->y -= v.y;
  27. };
  28. void scale(const float v)
  29. {
  30. this->x *= v;
  31. this->y *= v;
  32. };
  33. vec2 rotate(const double angle) const
  34. {
  35. vec2 result(x * cos(angle) - y * sin(angle),
  36. x * sin(angle) + y * cos(angle));
  37. return result;
  38. };
  39. double magnitude() const
  40. {
  41. return sqrt(this->x * this->x + this->y * this->y);
  42. };
  43. double magnitudeSquared() const
  44. {
  45. return this->x * this->x + this->y * this->y;
  46. };
  47. vec2 &normalise()
  48. {
  49. double m = this->magnitude();
  50. if (m != 0.0)
  51. {
  52. this->x /= m;
  53. this->y /= m;
  54. }
  55. return *this;
  56. };
  57. vec2 unitVector() const
  58. {
  59. double m = this->magnitude();
  60. vec2 ret;
  61. if (m != 0.0)
  62. {
  63. ret.x = this->x / m;
  64. ret.y = this->y / m;
  65. }
  66. return ret;
  67. };
  68. vec2 normal() const
  69. {
  70. vec2 ret(this->y, -this->x);
  71. return ret.normalise();
  72. };
  73. double dot(const vec2 &v) const
  74. {
  75. return (this->x * v.x) + (this->y + v.y);
  76. };
  77. double cross(const vec2 &v) const
  78. {
  79. /* return the imaginary Z component */
  80. return (this->x * v.y) - (this->y * v.x);
  81. };
  82. };
  83. #endif /* PHYSICENGINE_VEC2_H */