Another math question (Well in my mind it is)
Author Message
Will George

 Posted: Visual C# General, Another math question (Well in my mind it is) Top
 Just alittle background before I start. I am working on a program for my LEGO NXT (I guess a Trademark should be here ) using Bram's source to talk to it (Thank you Bram!) Gee, I whould have never got to talk to it without it. OK, So i'm a old guy that still plays with toys.. I'm OK with it. Can I say I'm making it for my granddaughter I lie ALOT.. Anyway, I made a control that displays Compass direction from a '(float) in degrees' .. As in 0 to 360 degrees...(Yep, some more 'borrowed' code I found..) I'm OK with that too. ALOT of you folks much smarter than I am. I want to take X/Y output (state) from a Joystick (no twist stick that gives rotation) and approximate 0 to 360 degrees of rotation from the X/Y output from the Joystick. I'm using Direct Input to obtain the joystick data. If I knew math.. I'm sure it is easy! I can send my code but a bit large and just a bunch of thoughts I have now .. Thanks to all.. Have a great Day! Visual C#2

sirjis

 Posted: Visual C# General, Another math question (Well in my mind it is) Top
 What you describe is exactly what the inverse tangent function is for. In C#, the best way to implement this would be using the Math.Atan2 method, which takes the y and x coordinates (in that order) and returns an angle in radians from the x-axis between -pi and +pi. Radians (if you don't know) are a way of measuring angles where 0 radians = 0 degrees and pi radians = 180 degrees. So to convert from radians to degrees, you multiply by 180.0f and divide by Math.Pi.This will give you the angle in degrees counterclockwise from the x-axis in the range -180 to 180. You want degrees clockwise from the y-axis for compass directions. Since the y-axis is 90 degrees from the x-axis, you can do (compass angle) = 90 - (atan angle). This will now range from -90 degrees to 270 degrees, so if the resulting angle is less than 0, add 360 degrees to it (since the physical angle doesn't actually change when you add 1 full revolution to it).So, in code, you get:float x = getXInput();float y = getYInput();float angle = 90.0f - (float)(Math.Atan2(y, x) * 180.0 / Math.Pi);if (angle < -90.0f) angle += 360.0f;// now angle should be from 0 to 360, and is the compass angleNote that I haven't tested this, so I may have sign errors or something. That's been known to happen.Hope it helps!

Will George

 Posted: Visual C# General, Another math question (Well in my mind it is) Top
 Thank you very much for the reply. I guess I should have payed more attention in Trig classes! EDIT: I still thank you for your post! But it did not work for my program.. BUT got me started in the right direction! Thank You. I used .... double x = state.X; double y = state.Y; double newangle = 180.0 - Math.Atan2(x, y) * 180.0 / Math.PI; rotate = (float)Math.Round(newangle); IT WORKED! AMAZZZZZZZZZZZZZZING!