X-Git-Url: http://gitweb.pgornicz.com/gitweb.cgi?p=physics.git;a=blobdiff_plain;f=src%2Fmathw.cpp;h=eda47819fbfe6eea5f68763c221044967751c244;hp=830a33dd7fc2052752b60e9656fa900522cdb0fe;hb=aa2791cf43a9ddd3a288e504db08e11d03439653;hpb=4a76d2e2cf7874e54a4e6688ebf1fa8ca59ce8c1 diff --git a/src/mathw.cpp b/src/mathw.cpp index 830a33d..eda4781 100644 --- a/src/mathw.cpp +++ b/src/mathw.cpp @@ -27,6 +27,35 @@ int mod(int x, int y) // Vector2 Math +Vector2 vectorToLine +( + const Vector2& vec, + float x1, + float y1, + float x2, + float y2 +) +{ + float lineSize = (float) sqrt((x1 - x2) * (x1 - x2) + + (y1 - y2) * (y1 - y2)); + if (lineSize == 0) + return Vector2(x1 - vec.x, y1 - vec.y); + + float u = ((vec.x - x1) * (x2 - x1) + + (vec.y - y1) * (y2 - y1)) / (lineSize * lineSize); + + if (u < 0) + return Vector2(x1 - vec.x, y1 - vec.y); + else if (u > 1) + return Vector2(x2 - vec.x, y2 - vec.y); + else + { + float ix = x1 + u * (x2 - x1); + float iy = y1 + u * (y2 - y1); + return Vector2(ix - vec.x, iy - vec.y); + } +} + Vector2 perp(const Vector2& vec) { return Vector2(-vec.y, vec.x);