I would like to rotate my transform by exactly 180 degrees from its current rotation, but be able to set the speed at which it rotates there. I am using a key input to trigger this, think of it as a “turn around” key to get the character to face the opposite way whenever the key is pressed once (not held down).
At the moment I am using the following Quaternion Lerp:
hero.rotation = Quaternion.Lerp(hero.rotation, Quaternion.AngleAxis(180, Vector3.up), Time.deltaTime * turnAroundSpeed);
But I always rotate to the same angle, instead of having the angle added onto my current rotation. If I use transform.Rotate the character simply snaps to the angle and I cannot control the speed it rotates at. How could I do this?
Use a coroutine like MoveObject:
MoveObject.use.Rotation (transform, Vector3.up * 180.0, turnAroundTime);
Specifically, the end rotation is essentially achieved like this:
endRotation = startRotation * Quaternion.Euler (degrees);
An alternative one script solution to the above, and the solution I ended up using is the Mathf.MoveTowardsAngle. It takes a few more steps to set up but worked better for me in the end.
Since it works with euler angles it’s easy to grab the current euler angle (in my case y) and add 180 degrees (or whatever you want) to it in the update function. Because I wanted the ‘turn around’ to happen on a button/key press, I had the above calculation made on the GetButtonDown/GetKeyDown, as otherwise the angle calculation wouldn’t stop and so neither would the rotation. I had the actual rotation called in GetButton/GetKey with the Mathf.MoveTowardsAngle, after the angle calculation. In order for the character to complete the rotation, the speed variable can be set quite high.