Rotate object over time, 90 degrees at a time

I checked other similar questions and code examples, but I could not find something suitable to my situation.

I need to rotate an object (smoothly) by 90° at a time upon certain events (for example, hitting a key or clicking with a mouse button).

I have a function which does roate the object by 90°, but not smoothly:

transform.Rotate(0, 90, 0);

how can I make it rotate smoothly?

2 Answers

2

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.

what is newAngle, i tried using this script but it does not recognise it

What is curAngle? Please explain its purpose because it's not defined anywhere

transform.Rotate rotates the object at a speed. You could say:

var RotSpeed = 2.0;

transform.Rotate(0, Rotspeed, 0);
if(transform.rotation.y >= 90){
   transform.rotation = 90;

}

or just a little change if the code above lets the object behave weird, you could say:

var rotated = false;

if(!rotated){
   transform.Rotate(0, Rotspeed, 0);
}

if(transform.rotation.y >= 90){
   transform.rotation.y = 90;
   rotated = true;

}

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.