Sort points by angle from given axis?

前端 未结 8 2871
無奈伤痛
無奈伤痛 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:25

    You should first normalize each vector, so each point is in (cos(t_n), sin(t_n)) format. Then calculating the cos and sin of the angles between each points and you reference point. Of course:

    cos(t_n-t_0)=cos(t_n)cos(t_0)+sin(t_n)sin(t_0)  (this is equivalent to dot product)
    sin(t_n-t_0)=sin(t_n)cos(t_0)-cos(t_n)sin(t_0)
    

    Only based on both values, you can determine the exact angles (-pi to pi) between points and reference point. If just using dot product, clockwise and counter-clockwise of same angle have same values. One you determine the angle, sort them.

提交回复
热议问题