- Home /
How can I rotate the transform by a specific angle at a certain speed?
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?
Answer by Eric5h5 · Nov 03, 2012 at 03:07 AM
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);
Thanks a lot for your help Eric5h5. So from the information in the link above it seems I would need to attach a separate "$$anonymous$$oveObject" script and then access it from my script using your suggestions above, correct? I also found the following (Add 90 degrees to transform.Rotation) on U.A. which deals with adding specific degrees to the transform, I haven't tested it yet in C# since it's in JS. Would this be a simpler solution?
Yes, I'd suggest putting the $$anonymous$$oveObject script on an empty game object. It's simpler since it's already written, so you just need to call it using one line of code when you want to rotate something.
$$anonymous$$arking this as "Accepted" since it was the first correct answer, even though it wasn't the actual solution I ended up using ;)
Answer by Hamesh81 · Nov 04, 2012 at 04:08 PM
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.