# Relative Rotation of GameObject

For my 2D game, I want to rotate my game object based on facing other game object.

One way to achieve this, I find

transform.LookAt(Vector3)

Using this way object also got rotated in z index also but at present I am targeting 2d games only. So what is the better way to constantly look for ratation?

Take a look at this:
Quaternion.LookRotation.
LookRotation lets you choose the facing vector. Play around with the parameters and you will find a solution.

If you’re only gonna be using 2d rotation, another way to do this is using Atan2.
You can set the z rotation value to angle you get from the above. Play around with the sign of the angle to get the correct result.

If the z coordinate is something else than what your looking object has, don’t look directly at it, but at a position with the same z coordinate.

``````Vector3 pos = target.transform.position;
pos.z = transform.position.z;
transform.LookAt(pos);
``````

A typical solution to the 2D rotation problem is to use Atan2().

``````var dir = target.transform.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
``````

This code assumes that the ‘forward’ that you want to point at the object is the right side of the object when the rotation is (0,0,0). If it is the top of the object, you will have to make an adjustment in the angle after calculating the angle.