# Rotating a specific axis towards a object

Hello everyone!

After a few hours of research, i was not able to find a solution to my problem.
I would like to make my 2D sprite “look at” another 2D sprite and then go towards it. But i am stuck with the rotating, i tried using LookAt() but then the sprite rotates on a wrong axis and the sprite flies out of the picture.

So basicly i just want it to rotate towards the other sprite but only on the Z-axis.

@Owne Reynolds mentions the typical solution, but I’ve found it does not work when you want to rotate around the ‘Z’ axis. It does look in the right place, but it can result in the object flipping. As an alternate solution, you can use Mathf.Atan2() and do your rotations in 2D. The following code assumes the right side of your object is what you want to look at the target. If you are using a plane, consider creating a vertical plane using the CreatePlane editor script.

#pragma strict

``````var target : Transform;
var speed = 0.75;

function Update() {
var v3Dir = target.position - transform.position;
var angle = Mathf.Atan2(v3Dir.y, v3Dir.x) * Mathf.Rad2Deg;
transform.eulerAngles = Vector3(0,0,angle);

if (Input.GetKey(KeyCode.W))
transform.Translate(Vector3.right * speed * Time.deltaTime);

}
``````

I tossed in a Translate towards the target when the ‘W’ key is pressed.

I fixed this myself by switching to Orthello 2D Framework and using a built in feature for sprites called RotateTowards()!

using UnityEngine;
using System.Collections;
public class AISmoothLookAT : MonoBehaviour {
public Transform target;
public Transform looker;
public Transform Xsmoothlooker;
public Transform Ysmoothlooker;
public float Xspeed = 2f;
public float Yspeed = 2f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
looker.LookAt (target);
float YRotation = looker.eulerAngles.y;
float XRotation = looker.eulerAngles.x;
Xsmoothlooker.rotation = Quaternion.Slerp(Xsmoothlooker.rotation , Quaternion.Euler(0 , YRotation, 0), Time.deltaTime * Xspeed);
Ysmoothlooker.rotation = Quaternion.Slerp(Ysmoothlooker.rotation , Quaternion.Euler(XRotation , YRotation, 0), Time.deltaTime * Yspeed);
}
}