Rick Rat
Rick Rat

Reputation: 1732

Calculate the angle of a click point

I am making a WPF control (knob). I am trying to figure out the math to calculate the angle (0 to 360) based on a mouse click position inside the circle.

For instance, if I click where the X,Y is on the image, I would have a point X,Y. I have the centerpoint as well, and cannot figure out how to get the angle.

circle image

My code below:

internal double GetAngleFromPoint(Point point, Point centerPoint)
{
    double dy = (point.Y - centerPoint.Y);
    double dx = (point.X - centerPoint.X);

    double theta = Math.Atan2(dy,dx);

    double angle = (theta * 180) / Math.PI;

    return angle;
}

Upvotes: 10

Views: 4146

Answers (3)

Clemens
Clemens

Reputation: 128061

The correct calculation is this:

var theta = Math.Atan2(dx, -dy);
var angle = ((theta * 180 / Math.PI) + 360) % 360;

You could also let Vector.AngleBetween do the calculation:

var v1 = new Vector(dx, -dy);
var v2 = new Vector(0, 1);
var angle = (Vector.AngleBetween(v1, v2) + 360) % 360;

Upvotes: 2

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

You've got it almost right:

internal double GetAngleFromPoint(Point point, Point centerPoint)
{
    double dy = (point.Y - centerPoint.Y);
    double dx = (point.X - centerPoint.X);

    double theta = Math.Atan2(dy,dx);

    double angle = (90 - ((theta * 180) / Math.PI)) % 360;

    return angle;
}

Upvotes: 9

Nico Schertler
Nico Schertler

Reputation: 32597

You need

double theta = Math.Atan2(dx,dy);

Upvotes: 3

Related Questions