x


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);
}
more ▼

asked Dec 15 '09 at 02:16 PM

Jaywalker gravatar image

Jaywalker
544 16 21 30

please format your code sample by indenting the entire block with four spaces (and each subsequent indent should also be four spaces!).

Dec 15 '09 at 02:44 PM duck ♦♦

Thanks, srry for the indent..

Dec 15 '09 at 04:49 PM Jaywalker
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Dec 15 '09 at 02:40 PM

duck gravatar image

duck ♦♦
45.7k 109 164 426

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,(Mathf.Atan2(verAxis , horAxis) * Mathf.Rad2Deg)); }

thanks again!

Dec 15 '09 at 04:51 PM Jaywalker
(comments are locked)
10|3000 characters needed characters left

If you're not interested in the angle value and just want a quaternion, you can also use Quaternion.LookRotation() or Quaternion.FromToRotation().

more ▼

answered Dec 16 '09 at 08:37 AM

mike gravatar image

mike
11 1

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x7780
x3213

asked: Dec 15 '09 at 02:16 PM

Seen: 2091 times

Last Updated: Dec 15 '09 at 04:36 PM