how to rotate an object to a certain angle unity2d code example
Example 1: unity 2d rotate towards direction
private void RotateGameObject(Vector3 target, float RotationSpeed, float offset)
{
Vector3 dir = target - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, RotationSpeed * Time.deltaTime);
}
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)); } } }