The easiest way is to use eulerAngles and a coroutine: calculate the desired new angle and fire a coroutine that will rotate automatically over time. To avoid other coroutines being fired while the first one is still running, you must set a boolean flag at the beginning, abort other calls while it’s set and clear the flag upon return:
var speed:float = 90.0; // degrees per second
private var curEuler:Vector3;
private var rotating:boolean = false;
function Start(){
curEuler = transform.eulerAngles;
}
function RotateAngle(angle: float){
if (rotating) return; // ignore calls to RotateAngle while rotating
rotating = true; // set the flag
var newAngle = curAngle.y+angle; // calculate the new angle
while (curEuler.y < newAngle){
// move a little step at constant speed to the new angle:
curEuler.y = Mathf.MoveTowards(curEuler.y, newAngle, speed*Time.deltaTime);
transform.eulerAngles = curEuler; // update the object's rotation...
yield; // and let Unity free till the next frame
}
rotating = false;
}
Just call the function RotateAngle(desiredAngle) and it will rotate the desired degrees automatically.
This worked great for me. I have a character that should turn around in 90 degrees just pressing any left or right axis. The only thing that i gotta check out was that it didn't work for rotating to the other side or negative angles RotateAngle(-90), but is not hard to do: change: var newAngle = curAngle-angle; while(curEuler.y > newAngle) and that's it.
transform.rotation is a quaternion, and its components are always between -1 and 1. You should use transform.eulerAngles, which is transform.rotation converted to/from the 3 axes Euler angles representation.
This worked great for me. I have a character that should turn around in 90 degrees just pressing any left or right axis. The only thing that i gotta check out was that it didn't work for rotating to the other side or negative angles RotateAngle(-90), but is not hard to do: change: var newAngle = curAngle-angle; while(curEuler.y > newAngle) and that's it.
– pabloromoclwhat is newAngle, i tried using this script but it does not recognise it
– nath23725652What is curAngle? Please explain its purpose because it's not defined anywhere
– WikiMalik