LookAt only on Z Axis

Hey guys, I’m trying to get an object to look at a player. The object moves with the player, however the problem is that it moves on the X and Y axis when I want it to just look at the Z axis.

public class FollowAim : MonoBehaviour {

private GameObject targetOBJ;
private Transform targetTRA;


// Update is called once per frame
void Update () {

	targetOBJ = GameObject.FindGameObjectWithTag("Player");
	targetTRA = targetOBJ.transform;
	this.transform.LookAt(targetTRA);
}

}

Is there any way to get the object to JUST rotate on the Z axis?

Hi @bishop87,
If you want to just rotate on the Z axis, don’t use the LookAt() method, it uses all axes by default.

in your Update(), replace the line with LookAt to this:

Vector3 difference = targetTRA.position - transform.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);

If you need more info, I made a tutorial with an example project here:
http://blog.iss.io/?p=26

If you want to use “transform.lookat” you can always make a new vector and keep the object’s transform in one or more of the axises, this is what i often do:

public Transform target;    
        
void Update() {

     transform.LookAt (new Vector3 (target.position.x, transform.position.y, target.position.z));
}

You should be able to change the “transform.position” on any axis you want to keep on the original position.