How to calculate an angle from points?

前端 未结 5 1710
天涯浪人
天涯浪人 2020-12-02 22:03

I want to get a simple solution to calculate the angle of a line (like a pointer of a clock).

I have 2 points:

cX, cY - the center of the line.
eX, e         


        
5条回答
  •  情歌与酒
    2020-12-02 22:57

    One of the issue with getting the angle between two points or any angle is the reference you use.

    In maths we use a trigonometric circle with the origin to the right of the circle (a point in x=radius, y=0) and count the angle counter clockwise from 0 to 2PI.

    In geography the origin is the North at 0 degrees and we go clockwise from to 360 degrees.

    The code below (in C#) gets the angle in radians then converts to a geographic angle:

        public double GetAngle()
        {
            var a = Math.Atan2(YEnd - YStart, XEnd - XStart);
            if (a < 0) a += 2*Math.PI; //angle is now in radians
    
            a -= (Math.PI/2); //shift by 90deg
            //restore value in range 0-2pi instead of -pi/2-3pi/2
            if (a < 0) a += 2*Math.PI;
            if (a < 0) a += 2*Math.PI;
            a = Math.Abs((Math.PI*2) - a); //invert rotation
            a = a*180/Math.PI; //convert to deg
    
            return a;
        }
    

提交回复
热议问题