I’m attempting to use Quaternion.Lerp to rotate a reset button smoothly when pressed. I have produced code that successfully rotates the object the first time I interact with it, but after that the object seems to randomly rotate backwards, and sometimes not rotate at all. How can I improve my code so that it consistently always rotates in the proper direction? Here is what I have right now.
using UnityEngine;
using System.Collections;
public class TestRotate : MonoBehaviour {
float smooth = 10.0f;
public Quaternion newRotation;
public Quaternion oldRotation;
public Vector3 newRotationAngles;
public GameObject resetButton;
// Use this for initialization
void Start ()
{
oldRotation = resetButton.transform.rotation;
newRotationAngles = oldRotation.eulerAngles;
newRotation = Quaternion.Euler (newRotationAngles);
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButtonDown (0))
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast (ray, out hit))
{
if(hit.transform.name == "Restart Button")
{
oldRotation = resetButton.transform.rotation;
newRotationAngles = oldRotation.eulerAngles;
newRotationAngles = new Vector3(0, 0, newRotationAngles.z + 180);
newRotation = Quaternion.Euler (newRotationAngles);
}
}
}
resetButton.transform.rotation = Quaternion.Lerp (resetButton.transform.rotation, newRotation, Time.deltaTime * smooth);
}
}