Help with rotating object

Here’s what I have:

using UnityEngine;
using System.Collections;

public class MapRotation : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
if (Input.GetKeyDown (“q”))
{
transform.Rotate (transform.rotation.x,transform.rotation.y,transform.rotation.z-90);
}
}

}

Even though I’m telling it to rotate exactly 90 degrees, the object actually rotates by 90.7071 degrees. By the 3rd rotate, the object is visibly messed up due to this.
How do I fix this to ensure that it is rotating exactly 90.0000 degrees?

Code tags. Absolutely necessary, but because this is so short, I’ll answer: floats have a certain “floatiness” to them that does not lend them to this kind of precise calculation ( or checking exact equality like “if(someFloat == 0f){}” ). If you want to rotate in exact increments, you need to do some rounding (Mathf.RoundToInt()) or parse the current rotation into an “int” and assign it back again.

in practice what lysander said
instead of

transform.Rotate (transform.rotation.x,transform.rotation.y,transform.rotation.z-90);

do

transform.Rotate (transform.rotation.x,transform.rotation.y,Mathf.Round(transform.rotation.z-90));

Well I just tried
private int Rotated = 90;
and then transform.rotation.z-Rotated;
And it is still going beyond 90 degrees.

Just tried that, but it’s rounding up because it was 90.7071

its not problem with 90 as that is int even in your script, problem is with unity and transform.rotation.z.
mathf.round should do the trick i think

:face_with_spiral_eyes: its rounding because it is 90.7071?

Sigh
Why can’t this be simple. I’ve finally figured out a game design that should be relatively easy to code, and my arse is still getting kicked.

hahahaha welcome to the club.
try

transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z - 90);

this doesnt rotate but set the rotation also if needed, add mathf.round at z calculation

1 Like

Thanks a ton. It doesn’t do 90.00000 but the decimal is so small that the eye can’t tell the difference.
Seriously, thank you.

I would check that the initial rotation is properly zeroed out. Also, because this question is now slightly annoying me in its refusal to be solved, I made the following:

public Vector3 RoundToNearest90Degrees(Vector3 oldAngle)
{
    int newX = Mathf.RoundToInt(oldAngle.x / 90) * 90;
    int newY = Mathf.RoundToInt(oldAngle.y / 90) * 90;
    int newZ = Mathf.RoundToInt(oldAngle.z / 90) * 90;

    return new Vector3(newX, newY, newZ);
}

This is for the eulerAngles, not the quaternion rotation.

1 Like

I genuinely hope to one day be half the coder you two are.

1 Like

Hahahhahahhahhaha. Thanks mate, nice to hear but I am really new. This is basic stuff. I try to help as much as i can with examples