- Home /
getAxis to rotation
Hey,
I would like to convert an Axis value like x1 y1 to an angle value like 45 degrees. Atm i "solved" this with a long if else but there has to be a better way of doing it?
thanks!
if (horAxis > 0) { crossHair.rotation = Quaternion.Euler (0, 0,0); }else if (horAxis < 0) { crossHair.rotation = Quaternion.Euler (0, 0,180); }
if (verAxis >0) { crossHair.rotation = Quaternion.Euler (0, 0,90); }else if (verAxis <0) { crossHair.rotation = Quaternion.Euler (0, 0,-90); }
if (horAxis > 0 && verAxis > 0) { crossHair.rotation = Quaternion.Euler (0, 0,45); } if (horAxis < 0 && verAxis < 0) { crossHair.rotation = Quaternion.Euler (0, 0,-135); } if (horAxis > 0 && verAxis < 0) { crossHair.rotation = Quaternion.Euler (0, 0,-45); } if (horAxis < 0 && verAxis > 0) { crossHair.rotation = Quaternion.Euler (0, 0,135); }
please format your code sample by indenting the entire block with four spaces (and each subsequent indent should also be four spaces!).
Answer by duck · Dec 15, 2009 at 02:40 PM
If it's just two values representing a 2d vector (as in your example, x=1, y=1), you can use the Atan2 function provided in the Mathf collection of functions like this:
crossHair.rotation = Mathf.Atan2( horAxis, verAxis ) * Mathf.Rad2Deg;
Notice that you need to multiply the result by a special constant called Rad2Deg, because the result of Atan2 is in radians, wheras rotation values in Unity are measured in degrees.
You may find that you need to swap the input around or invert the values to get the final desired rotation, eg: (-verAxis, horAxis) or something similar.
Thanks a lot! i got a console error about not being able to convert to a float, so i changed it to the following:
crossHair.rotation = Quaternion.Euler(0,0,($$anonymous$$athf.Atan2(verAxis , horAxis) * $$anonymous$$athf.Rad2Deg)); }
thanks again!
Answer by mike.du · Dec 16, 2009 at 08:37 AM
If you're not interested in the angle value and just want a quaternion, you can also use Quaternion.LookRotation() or Quaternion.FromToRotation().
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
how do i make an object always face the player? 5 Answers
Problem with Z rotation when rotating X and Y and the same time. 2 Answers
Animating (simple rotation) armature by script 1 Answer
Making an object stay parallel to the terrain it is on? 2 Answers