Find the center (of mass) of a 2D complex polygon

Griffin picture Griffin · Sep 14, 2011 · Viewed 7.9k times · Source

so i'm wondering what the algorithm for finding a shapes center of mass if I have a set of vertices?

Also if it makes the algorithm shorter my complex polygons are saved as a set of simple convex polygons, and you can get their vertices.

an image

I found the above equation but i don't know how to translate it......

Answer

corsiKa picture corsiKa · Sep 14, 2011

In light of new evidence, I firmly believe your given formula is wrong. Allow me to provide a different algorithm. I tried to make it look C++ish, but I'm sure I got some things wrong. If you'd like to nitpick about those, that's fine. If you'd like to downvote on them, I can't stop you, but I'd rather you edit them away to make the post better. :-)

// use doubles if appropriate
float xsum = 0.0;
float ysum = 0.0;
float area = 0.0;
for(int i = 0; i < points.size - 1; i++) {
    // I'm not a c++ guy... do you need to use pointers? You make the call here
    Point p0 = points[i];
    Point p1 = points[i+1];

    double areaSum = (p0.x * p1.y) - (p1.x * p0.y)

    xsum += (p0.x + p1.x) * areaSum;
    ysum += (p0.y + p1.y) * areaSum;
    area += areaSum;
}

float centMassX = xsum / (area * 6);
float centMassY = ysum / (area * 6);