- Home /
Set Rotation back to Zero with animation on keypress
I want to set the rotation of an object back to (0,0,0) slowly irrespective of the current rotation degree. Here is the code that I use to rotate back my object to zero:
if (Input.GetKeyDown(KeyCode.R))
{
MiniMapCube.transform.rotation = new Quaternion(0, 0, 0, 0);
}
Any suggestions?
Comment
Sounds like you want to rewind time https://m.youtube.com/watch?v=eqlHpPzS22U
Best Answer
Answer by z-salem · Jan 01, 2019 at 04:07 PM
I could solve it. maybe not an optimal solution but it works.
private IEnumerator ResetRotation(float duration)
{
rotating = true;
Quaternion startRotation = MiniMapCube.transform.rotation;
Vector3 vec3;
vec3 = new Vector3(MiniMapCube.transform.rotation.eulerAngles.x*-1, MiniMapCube.transform.rotation.eulerAngles.y*-1, MiniMapCube.transform.rotation.eulerAngles.z*-1);
Quaternion endRotation = Quaternion.Euler(vec3) * startRotation;
for (float t = 0; t < duration; t += Time.deltaTime)
{
MiniMapCube.transform.rotation = Quaternion.Lerp(startRotation, endRotation, t / duration);
yield return null;
}
MiniMapCube.transform.rotation = new Quaternion(0, 0, 0, 0);
rotating = false;
}
In update call the function above on keypress:
if (Input.GetKeyDown(KeyCode.R))
{
if (!rotating)
StartCoroutine(ResetRotation(0.5F));
}