Multiple keydowns/coroutines cause unwanted angles in objects
I'm fairly new to unity, but after scraping through the threads about rotations throughout frames, I managed to scoop up this code for rotating this octagon by 45 degrees:
public class Movement : MonoBehaviour
{
IEnumerator RotateOctagon(Vector3 byAngles, float inTime)
{
var fromAngle = transform.rotation;
var toAngle = Quaternion.Euler(transform.eulerAngles + byAngles);
for(var t = 0f; t <= 1; t+= Time.deltaTime / inTime)
{
transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t);
yield return null;
}
transform.rotation = toAngle;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("left"))
{
StartCoroutine(RotateOctagon(Vector3.forward * 45, 0.1f));
}
if (Input.GetKeyDown("right"))
{
StartCoroutine(RotateOctagon(Vector3.forward * -45, 0.1f));
}
if (Input.GetKeyDown("up"))
{
StartCoroutine(RotateOctagon(Vector3.forward * 180, 0.1f));
}
}
}
And it generates desired results, assuming you wait until the rotation is finished...
But The problem arises when you press left or right in the middle of the animation, in which the octagon incorrectly ends up on a point or weird angle (not a multiple of 45 degrees)...
I considered calculating the offset of the angle to the lower/higher 45 degree angle multiple, but I feel like there's a more correct approach and something I'm missing about coroutines - I had thought that one coroutine happends only after the other one finishes.
Any help on how to get the octagon (and pipe around it) to rotate properly would be greatly appreciated.
edit: I've also considered simplifying this code since It's only being rotated on a single axis by using Mathf.MoveTowardAngle, but this is the closest I've gotten to getting the look I want.
Your answer
Follow this Question
Related Questions
Rotating an Object (To Face Another Object) Only on X and Y Axis 3 Answers
Rotate camera on collision of character 1 Answer
Cancel out the steering rotation returned from a wheel colliders .GetWorldPose(out pos, out rot); 1 Answer
Space/Aircraft rotation 0 Answers
Camera Controller script as a child object,Camera Control as a Child Object for my Player 0 Answers