Center of gravity of a polygon

后端 未结 7 921
遥遥无期
遥遥无期 2020-12-02 16:13

I am trying to write a PHP function that will calculate the center of gravity of a polygon.

I\'ve looked at the other similar questions but I can\'t seem to find a s

7条回答
  •  再見小時候
    2020-12-02 16:36

    in cold c++ and while assuming that you have a Vec2 struct with x and y properties :

    const Vec2 findCentroid(Vec2* pts, size_t nPts){
        Vec2 off = pts[0];
        float twicearea = 0;
        float x = 0;
        float y = 0;
        Vec2 p1, p2;
        float f;
        for (int i = 0, j = nPts - 1; i < nPts; j = i++) {
            p1 = pts[i];
            p2 = pts[j];
            f = (p1.x - off.x) * (p2.y - off.y) - (p2.x - off.x) * (p1.y - off.y);
            twicearea += f;
            x += (p1.x + p2.x - 2 * off.x) * f;
            y += (p1.y + p2.y - 2 * off.y) * f;
        }
    
        f = twicearea * 3;
    
        return Vec2(x / f + off.x, y / f + off.y);
    }
    

    and in javascript :

    function findCentroid(pts, nPts) {
        var off = pts[0];
        var twicearea = 0;
        var x = 0;
        var y = 0;
        var p1,p2;
        var f;
        for (var i = 0, j = nPts - 1; i < nPts; j = i++) {
            p1 = pts[i];
            p2 = pts[j];
            f = (p1.lat - off.lat) * (p2.lng - off.lng) - (p2.lat - off.lat) * (p1.lng - off.lng);
            twicearea += f;
            x += (p1.lat + p2.lat - 2 * off.lat) * f;
            y += (p1.lng + p2.lng - 2 * off.lng) * f;
        }
        f = twicearea * 3;
        return {
        X: x / f + off.lat,
        Y: y / f + off.lng
        };
    }
    

    or in good old c and while assuming that you have a Point struct with x and y properties :

    const Point centroidForPoly(const int numVerts, const Point* verts)
    {
        float sum = 0.0f;
        Point vsum = 0;
    
        for (int i = 0; i

提交回复
热议问题