# Rotating an object towards target on a single axis

I need to rotate an 2d sprite towards it’s target - another sprite, only using the Z axis. The target can only move on the X and Y axis, I need the object to always face it with it’s front.

I tried using Quaternion.LookRotation , converting it to eulerAngles and setting z and y to 0:

``````function Update () {
var relativePos = target.position - transform.position;
var rotation = Quaternion.LookRotation(relativePos).eulerAngles;
transform.rotation = Quaternion.Euler(0,0,rotation.z);

}
``````

but for some reason it doesn’t rotate on the Z axis at all (rotation.z always stays at zero) no matter where the target is.

I also tried this:

``````   var relative : Vector3  = transform.InverseTransformPoint(target.position);

var angle : float = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg;

var rotation = Quaternion.Euler (0, 0, angle);

transform.rotation = rotation;
``````

The object does rotate on the Z axis now, but instead of turning towards the target it rotates to random directions.

c#

``````// fast rotation
float rotSpeed = 360f;

// distance between target and the actual rotating object
Vector3 D = target.position - transform.position;

// calculate the Quaternion for the rotation
Quaternion rot = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(D), rotSpeed * Time.deltaTime);

//Apply the rotation
transform.rotation = rot;

// put 0 on the axys you do not want for the rotation object to rotate
transform.eulerAngles = new Vector3(0, 0,transform.eulerAngles.z);
``````

java

``````// fast rotation
var rotSpeed : float = 360;

// distance between target and the actual rotating object
var D : Vector3 = target.position - transform.position;

// calculate the Quaternion for the rotation
var rot : Quaternion = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(D), rotSpeed * Time.deltaTime);

//Apply the rotation
transform.rotation = rot;

// put 0 on the axys you do not want for the rotation object to rotate
transform.eulerAngles = new Vector3(0, 0,transform.eulerAngles.z);
// not quite sure if the "new" is needed on java
``````

Well, just looking at the reference for Quaternion.LookRotation we can see that it:

`````` LookRotation (Vector3 forward, Vector3 upwards)
``````

creates a rotation that looks along
forward with the the head upwards
along upwards

I don’t see where you define “upwards” in your code so I can only assume that you’re letting that slip through JS’s ability to handle that sort of stuff. But have you tried replacing “upwards” with Vector3.Forward? If you do, all the other stuff you have mashed in there won’t matter.

LookRotation is really supposed to do what you want without any hand holding at all really.