简体   繁体   中英

How can I find a circle angle from x and y axis

Feel free to mark my question duplicated. Because I know absolute nothing about COS, SIN, and TAN and someone else probably already ask this question.

So, I was try to set the circular progress bar based on x and y axis that can get from gamepad input. The progress bar put it simple is just a Minimum of 0 and maximum of 360.

I did try to search a bit, but my best understanding is that it work with only 180 degree and positive x and y. But the input I get from the controller is and y from -1 to 1 (where x -1 is left and 1 is right, y -1 is bottom and 1 is top)

Here is my code so far.

var controller = Windows.Gaming.Input.Gamepad.Gamepads[0].GetCurrentReading();
x = controller.LeftThumbstickX
y = controller.LeftThumbstickY
//what do I have to do from here?
progress.Value = angle; //?

The trigonometric function atan2 is the tool for this job. In C#, this is implemented by Math.Atan2 :

double angleInRadians = Math.Atan2(y, x);
double angleInDegrees = (180 / Math.PI) * angleInRadians;

Using this formula with (for instance) parameters (1,1) , you'll get a result of 45.

However, in terms of polar alignment, this angle measures anti-clockwise from "east". To convert this to an angle that measures clockwise from "north":

double compassRadians = Math.PI / 2 - angleInRadians;
double compassDegrees = (180 / Math.PI) * compassRadians;

but now we may encounter negative values, so we can normalize them with the following method:

double normalizeDegrees(double a) => ((a % 360) + 360) % 360; //convert to 0-360

then

var compassAngle = normalizeDegrees(compassDegrees);

The method you want is Math.Atan2 . This takes two arguments - the y-value first, then the x-value - and it gives you an angle in radians.

Since you want an angle in degrees, you'll need to convert - the conversion factor is 180 / Math.PI . So you'll be using something like:

var radiansToDegrees = 180 / Math.PI;
progress.Value = Math.Atan2(y,x) * radiansToDegrees;

Depending exactly what combination of x and y needs to correspond to 0 you might need to add a number of degrees on afterwards. This as-is will give you 0 degrees for x = 1, y = 0, and 90 degrees for x = 0, y = 1, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM