Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve a positive or a negative angle from 3 points

I am rotating points around a center point in 2D space. The points are the center point, the old mouse position, and the new mouse position. My rotation function works fine, and I can calculate the angle perfectly. But I want to calculate a negative angle if the user is moving their mouse in a direction which should be interpreted as counter-clockwise.

For example, moving the mouse toward the right (positive x-axis) should rotate clockwise if you are above (less than) the y value of the center point, but it should rotate counter-clockwise if you are actually below (greater than) the y value of the center point.

Here's what I have:

PointF centerPoint;
PointF oldPoint;
PointF newPoint;

double Xc = centerPoint.X;
double Yc = centerPoint.Y;
double Xb = oldPoint.X;
double Yb = oldPoint.Y;
double Xa = newPoint.X;
double Ya = newPoint.Y;

double c2 = (Math.Pow(Xb - Xa, 2) + Math.Pow(Yb - Ya, 2));
double a2 = (Math.Pow(Xb - Xc, 2) + Math.Pow(Yb - Yc, 2));
double b2 = (Math.Pow(Xa - Xc, 2) + Math.Pow(Ya - Yc, 2));

double a = Math.Sqrt(a2);
double b = Math.Sqrt(b2);

double val = (a2 + b2 - c2) / (2 * a * b);
double angle = Math.Acos(val);

So I need a way to make angle negative when it needs to be, so the points rotate clockwise or counter-clockwise to follow the mouse position.

like image 503
Trevor Elliott Avatar asked Jan 26 '12 17:01

Trevor Elliott


2 Answers

Try this, but I'm not sure:

double v1x = Xb - Xc;
double v1y = Yb - Yc;
double v2x = Xa - Xc;
double v2y = Ya - Yc;

double angle = Math.Atan2(v1x, v1y) - Math.Atan2(v2x, v2y);
like image 58
Ingemar Avatar answered Sep 20 '22 18:09

Ingemar


private double AngleFrom3PointsInDegrees(double x1, double y1, double x2, double y2, double x3, double y3)
{
    double a = x2 - x1;
    double b = y2 - y1;
    double c = x3 - x2;
    double d = y3 - y2;

    double atanA = Math.Atan2(a, b);
    double atanB = Math.Atan2(c, d);

    return (atanA - atanB) * (-180 / Math.PI); 
    // if Second line is counterclockwise from 1st line angle is 
    // positive, else negative
}
like image 23
Jim McGivney Avatar answered Sep 18 '22 18:09

Jim McGivney