- Home /
How do I rotate an object a certain number of degrees?
My goal is to rotate a GameObject a certain number of degrees. I currently have a script that rotates it indefinitely, or it should, but it slows down and stops at 180, though I did nothing to specify that. I assume there's something built into Unity that does that, which isn't a big deal, I can adjust the rotation in the Inspector manually beyond 180, but the script stops at 180, how can I have it rotate until it reaches a certain number of degrees even if that is past 180? (Also, the "rotation1" variable never goes past 1, I don't think I should need that, but it's odd that it doesn't go past 1.)
private var rotation1:float = 0;
function Reset () { transform.rotation.z = 0; }
function Update () {
transform.rotation.z = (transform.rotation.z + 1 * Time.deltaTime);
rotation1 = (transform.rotation.z);
print(rotation1);
if (rotation1 == 180) {
Reset();
}
}
Answer by robertbu · Apr 22, 2013 at 03:18 PM
Transform.rotation is a Quaternion...a 4D construct that you should not manipulate directly unless you fully understand quaternions. You can manipulate Transform.eulerAngles, but you have to be careful about how you do the manipulation. From the reference:
Do not set one of the eulerAngles axis separately (eg. eulerAngles.x = 10; ) since this will lead to drift and undesired rotations.
In addition, there are multiple euler angles that represent the same 'physical' rotation. So for example you could do something like...
transform.eulerAngles = Vector3(180,0,0);
...and if you immediately read back the value you might bet a reading of (0,180,180), which represents the same physical rotation.
One way to deal with Transform.eulerAngles is to manage it as "write-only." That maintain your own Vector3 value and set it when needed...and it will not stop at 180.
Thanks! I'm somewhat new to Unity, and prior to Unity all my scripting was done in Lua, so there's a lot of things that I end up doing wrong.
Answer by proandrius · Apr 22, 2013 at 03:47 PM
You should use transform.Rotate(new Vector3(0,0,1));
and if(Mathf.Round(transform.eulerAngles.z)==180) { transform.Rotate(new Vector3(0,0,-180)); }
Thank you so much! I was trying to get my head around this. Really, It's good to know the method library for unity to simplify things alot.