Pretty easy question, I think - rotation...

So I’m attempting for the first time to do a whole lot of javascripting myself for a unity project. I am creating a little 2-d style game with very simple back and forth movement. I actually have this working…the movement is fine, and I was able to get the character rotated the correct way by using:

transform.localEulerAngles.y=90;

…which was the “right” direction, 270 the left.

Now i’m trying to make the character “turn” until he faces the opposite direction. I have been using this to make him turn:

transform.Rotate(Vector3.up*Time.deltaTime*100);

It does work…now I want him to turn only if he’s not facing the direction he should be…so I tried THIS, and here is where I’m having the problem:

if (!(transform.localEulerAngles.y==90))
    {
    transform.Rotate(Vector3.up*Time.deltTime*100);
    }

Any thoughts as to why the player would rotate right from the start, even though the angle is 90 degrees right from the start? Any better methods? I’m sure there is a much more efficient way to achieve this…thanks!

I tried this in the editor and it looks like you’re running into floating-point precision errors. Floats can become off by really small amounts, so when you’re putting 90 into the value it’s storing that value as 90.00001. Since 90 does not equal 90.0001, it’s rotating around. One way to fix this is to check with an epsilon value, so you’d do something like:

if( transform.localEulerAngles.y - 90 > .001 )
{
   transform.Rotate( Vector3.up * Time.deltaTime * 100;
}

One other option is to use the forward vector. If your character is looking to the right, then their forward vector is (1, 0, 0). You could use the x-component of the forward vector to tell you which direction the character is looking.

Thanks dude! Worked like a charm. Thats one I definitely should’ve been able to tech myself! But thanks a lot for the quick help…saved me from banging my head against a wall over something simple for a few hours!