Sort points by angle from given axis?

前端 未结 8 2819
無奈伤痛
無奈伤痛 2021-02-19 12:11

How can I sort an array of points/vectors by counter-clockwise increasing angle from a given axis vector?

For example:

8条回答
  •  余生分开走
    2021-02-19 12:21

    This is an example of how I went about solving this. It converts to polar to get the angle and then is used to compare them. You should be able to use this in a sort function like so:

    std::sort(vectors.begin(), vectors.end(), VectorComp(centerPoint));
    

    Below is the code for comparing

    struct VectorComp : std::binary_function
    {
    
        sf::Vector2f M;
        IntersectComp(sf::Vector2f v) : M(v) {}
    
        bool operator() ( sf::Vector2f o1,  sf::Vector2f o2)
        {
            float ang1     = atan( ((o1.y - M.y)/(o1.x - M.x) ) * M_PI / 180);
            float ang2     = atan( (o2.y - M.y)/(o2.x - M.x) * M_PI / 180);
            if(ang1 < ang2) return true;
            else if (ang1 > ang2) return false;
            return true;
        }
    };
    

    It uses sfml library but you can switch any vector/point class instead of sf::Vector2f. M would be the center point. It works great if your looking to draw a triangle fan of some sort.

提交回复
热议问题