# How can I modify this script to restrict Z rotation?

Hi guys. So, I got the following script from this thread:

http://forum.unity3d.com/viewtopic.php?t=10871&highlight=limit+rotation

It is made to restrict movement along different axis while an object (turret probably) is “looking” at something. It works great for my purposes, except that I noticed that it allows a little bit of Z movement which I’ like to eliminate. Is it possible, with this function to add a restriction to Z movement to keep it locked at exactly 0 at all times?’

``````var target : Transform;
var damping = 5.0;
var xConstraint = 360;
var yConstraint = 30;

function Update () {
if (target) {
var rot = Quaternion.LookRotation(target.position - transform.position);
var rotationX = rot.eulerAngles.y;
var rotationY = rot.eulerAngles.x;
rotationX = ClampAngle(rotationX, -xConstraint, xConstraint);
rotationY = ClampAngle(rotationY, -yConstraint, yConstraint);
rotationY = -rotationY;
var xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
var yQuaternion = Quaternion.AngleAxis(rotationY, Vector3.left);
transform.localRotation = Quaternion.Slerp(transform.localRotation, xQuaternion * yQuaternion, Time.deltaTime * damping);
}
}

function ClampAngle(angle, min, max){
if (target){
if (min < 0) min += 360;
if (angle > 180){
return Mathf.Clamp(angle, min, 360);
} else {
return Mathf.Clamp(angle, 0, max);
}
}
}
``````

I tried adding “transform.eulerAngles.z = 0;” to the update loop, and while it works it seems like a hack and I also can see in the transform properties of my object, that it is constantly ‘fighting’ to stay at 0. I’d like the object to not even move off of 0 in the Z in the first place.

Thanks!

Add this to function Update() on the object: transform.eulerAngles.z = 0;

Edit: That’ll teach me to not read below the code.

Not sure if you’re just trying to be snarky, since I said specifically in my message, I didn’t want to do this.

Anyone else?

Is that really the best (most efficient) way to do this?

Well, due to the fact you’re rotating using Quaternions, I can’t exactly give you a math trick to make it work off the top of my head. That’s the main reason why all my rotation scripts rely on eulers.

Setting it to zero once a frame isn’t too expensive, so unless you’re using dozens of turrets simultaneously, it’s a fast and easy fix that won’t hurt you.