OSDN Git Service

Moar utils.
authorNathanSweet <nathan.sweet@gmail.com>
Wed, 11 Sep 2013 13:54:45 +0000 (15:54 +0200)
committerNathanSweet <nathan.sweet@gmail.com>
Wed, 11 Sep 2013 13:54:45 +0000 (15:54 +0200)
gdx/src/com/badlogic/gdx/math/GeometryUtils.java

index 8bc8485..d3986df 100644 (file)
@@ -62,4 +62,35 @@ public class GeometryUtils {
                return centroid;
        }
 
+       /** Returns the centroid for the specified non-self-intersecting polygon. */
+       public static Vector2 polygonCentroid (float[] polygon, int offset, int count, Vector2 centroid) {
+               float x = 0, y = 0;
+
+               float signedArea = 0;
+               int i = offset;
+               for (int n = offset + count - 2; i < n; i += 2) {
+                       float x0 = polygon[i];
+                       float y0 = polygon[i + 1];
+                       float x1 = polygon[i + 2];
+                       float y1 = polygon[i + 3];
+                       float a = x0 * y1 - x1 * y0;
+                       signedArea += a;
+                       x += (x0 + x1) * a;
+                       y += (y0 + y1) * a;
+               }
+
+               float x0 = polygon[i];
+               float y0 = polygon[i + 1];
+               float x1 = polygon[offset];
+               float y1 = polygon[offset + 1];
+               float a = x0 * y1 - x1 * y0;
+               signedArea += a;
+               x += (x0 + x1) * a;
+               y += (y0 + y1) * a;
+
+               signedArea *= 0.5f;
+               centroid.x = x / (6 * signedArea);
+               centroid.y = y / (6 * signedArea);
+               return centroid;
+       }
 }