Trigonometry Question: LookAt() lock axis

I’m trying to create some scripts that will attach to a tank model, so I made a general script that will face an axis to a position in world space, but the math isn’t mine, I copy pasted off of somebody elses tank controller script. The script works fine if I’m only using one axis, but messes up if you try to use more than one. Could you help me understand what I would need to do to have the script work on more than one axis?

    // You can only use one axis at a time, I need to fix this eventually
#pragma strict

var target : Transform ;
var LimitToY : boolean = false;
var LimitToX : boolean = false;
var LimitToZ : boolean = false;


function Update () {
	var targetVector : Vector3 = target.transform.position - transform.position;
	var localHeading : Vector3 = transform.InverseTransformDirection(targetVector);
	
	if (LimitToY){
		var requiredYaw : float = Mathf.Rad2Deg * Mathf.Atan2(localHeading.x, localHeading.z);
		transform.Rotate(Vector3.up, requiredYaw, Space.Self);
	}

	if (LimitToX){
		var requiredPitch : float = Mathf.Rad2Deg * Mathf.Atan2(localHeading.z, localHeading.y);
		transform.Rotate(Vector3.right, requiredPitch, Space.Self);
	}
	
	if (LimitToZ){
		var requiredRoll : float = Mathf.Rad2Deg * Mathf.Atan2(localHeading.y, localHeading.x);
		transform.Rotate(Vector3.forward, requiredRoll, Space.Self);
	}
}

It seems like it would be much easier to use transform.LookAt(). If you need to lock a particular axis, you can just make sure that the relevant vector component matches the original transform’s position.

var pos = target.transform.position;
if (LimitToX) pos.x = transform.position.x;
if (LimitToY) pos.y = transform.position.y;
if (LimitToZ) pos.z = transform.position.z;
transform.LookAt(pos);

This assumes that you want LimitToX and family to keep the turret from facing on that axis. If not, you can just flip all of those conditions: !LimitToX and so on.

@rutter,

I’ve tried implementing your answer so that my camera looks at my target.

My problem is that the camera has an initial rotation on the x-axis.
If I want to rotate around the y-axis only, then this method does work, but makes the camera look at a different position on the x (because the y pos of the target is now set to the camera)

What would I do if I wanted to keep the initial x and z rotation values of the camera and only modify the y value (so the target doesn’t need to be in the centre of the camera)

Sorry if my question isn’t clear