# Unity C# - Rotate smoothly an object towards the direction given by input

I am trying to rotate an object towards the direction given by de direction of the input. For example, if I am pressing 'up' of the directional pad, the player should rotate pointing that direction.

I've tried using Euler angles, and when I press the direction, I call a coroutine that sums the eulerAngle.y of the object till it gets the angle of the direction, but it doesn't work. I don't know if there is another approach to use.

Here is the code for the coroutine. It starts if a certain key is pressed and if a flag is not activated:

 IEnumerator rotateTowards(float angle)
{
rotating = true;
Debug.Log("Rotating the mono...");
float turningTime = 0.8f;
//float thisAngle = this.transform.eulerAngles.y;
Vector3 thisAngle = this.transform.eulerAngles;

if(thisAngle.y < angle)
{
while(thisAngle.y < angle)
{
thisAngle.y += turningTime * Time.deltaTime;
this.transform.eulerAngles = thisAngle;
}
}

if(thisAngle.y > angle)
{
while(thisAngle.y > angle)
{
thisAngle.y -= turningTime * Time.deltaTime;
this.transform.eulerAngles = thisAngle;
}
}

this.transform.eulerAngles = thisAngle;
rotating = false;
yield return null;
}


• Can I see the code surrounding the call of the coroutine? If you are using a coroutine to handle input, remember to stop the coroutine after the player releases the input. – DarkDestry Oct 10 '16 at 0:57

I don't see why you need a coroutine; I think you need Quaternion.Slerp().

Unity give an example of what you want to do in its documentation.

Have you tried using Debug.Log statements in your code to make sure that your code is even running? Try putting a while(true) statement and then stopping the coroutine when it's done?

First, euler angles aren't precise, everything gets internal converted to quaternions, second Unity has some smoothing on the default input controls, third, u may know but i dont see it in your example, you need to sue StartCouroutine("Name"); to use an IEnumerator.

Ill give you an example of the simplest solution i found

Update(){
float h=Input.GetAxis("Horizontal");//thies work with WASD or arrow keys + other things unity can use, gamepad etc..
float v=Input.GetAxis("Vertical");
if(v!=0||h!=0){// if we are getting inputs, form -1 to 1, 0=no input
Vector3 direction=(Vector3.forward*h)+(Vector3.right*v);// as the key is held down the h or v values will move toward full -1 or 1, thus handling the smooth rotation
transform.rotation=Quaternion.LookRotation(direction);
}
}