added suport for ballxpolygon collision ... VERY hacky
[physics.git] / src / mathw.cpp
index 830a33d..eda4781 100644 (file)
@@ -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);