smoothly rotate object unity code example
Example 1: unity smoothly rotate
private float desiredRot; public float rotSpeed = 250; public float damping = 10; private void OnEnable() { desiredRot = transform.eulerAngles.z; } private void Update() { if (Input.GetMouseButton(0)) { if (Input.mousePosition.x > Screen.width / 2) desiredRot -= rotSpeed * Time.deltaTime; else desiredRot += rotSpeed * Time.deltaTime; } var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y, desiredRot); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * damping); }
Example 2: unity rotate object 90 degrees smoothly
IEnumerator RotateMe(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.Slerp(fromAngle, toAngle, t); yield return null; } } void Update () { if(Input.GetKeyDown("e")){ StartCoroutine(RotateMe(Vector3.up * 90, 0.8f)); } if(Input.GetKeyDown("q")){ StartCoroutine(RotateMe(Vector3.up * -90, 0.8f)); } } }