vec2.cxx 387 B

12345678910111213141516
  1. #include <stdbool.h>
  2. #include <math.h>
  3. #include "vec2.h"
  4. // Returns the closest point to the line segment ab and p
  5. Vec2 Vec2_closest(const Vec2& a, const Vec2& b, const Vec2& p) {
  6. // vector along line ab
  7. Vec2 ab = b - a;
  8. float t = ab.dot(ab);
  9. if(t == 0.0f) {
  10. return a;
  11. }
  12. t = fmax(0.0f, fmin(1.0f, (p.dot(ab) - a.dot(ab)) / t));
  13. return a + ab * t;
  14. }