rotate towards unity 2d code example
Example 1: how to make a object rotate towards a position in 2d unity
Vector3 targ = staticCompassTarget.transform.position;
targ.z = 0f;
Vector3 objectPos = transform.position;
targ.x = targ.x - objectPos.x;
targ.y = targ.y - objectPos.y;
float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
Example 2: 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 3: 2d rotation unity
float x;
void Update ()
{
x += Time.deltaTime * 10;
transform.rotation = Quaternion.Euler(x,0,0);
}