# how to clamp the look at function?

how can i look at a target on 2 axis but clamp the the object's rotation ,to only rotate from -45 to 45 on x and from -60 to 60 on y axis. i used this script to look at target and clamp the rotation, but it's not working right ): there is no problem with maximum value but whenever the rotation is about to become zero or a negative value the wired problem will show up. i made a gif here (http://www.mediafire.com/view/55phgr5qrhy8fk1/record.gif)

public Transform target;
public float speed;

public float minimumX;
public float maximumX;

public float minimumY;
public float maximumY;
// Start is called before the first frame update
void Start()
{

}

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

Quaternion OriginalRot = transform.rotation;
transform.LookAt(target);
Quaternion NewRot = transform.rotation;
transform.rotation = OriginalRot;
transform.rotation = Quaternion.Lerp(transform.rotation, NewRot, speed * Time.deltaTime);

transform.eulerAngles = new Vector3(Mathf.Clamp(transform.eulerAngles.x, minimumX, maximumX), Mathf.Clamp(transform.eulerAngles.y, minimumY, maximumY), 0);

}


}

• You put minimumX as both arguments in the first clamp – Bálint Jun 11 '19 at 10:11
• ok, i fixed that one,but still it doesn't work right.when my camera is about to reach the minimum amount of rotations it shows some weird behavior – h00man13 Jun 11 '19 at 10:47
• i made a gif to show the problem – h00man13 Jun 11 '19 at 12:09

My guess that eulerAngles returns angle from 0 to 360, so "-1" is 359 and is clamped to maximumY.

Try this:

float ry = transform.eulerAngles.y;
if (ry >= 180) ry -= 360;
transform.eulerAngles = new Vector3 (
Mathf.Clamp(transform.eulerAngles.x, minimumX, maximumX),
Mathf.Clamp(ry, minimumY, maximumY),
0
);

• BEAUTIFUL, thanks man it works perfectly :) – h00man13 Jun 11 '19 at 13:14
• @h00man13 you can also upvote my answer if you like it, I'll get another +10 rep – trollingchar Jun 11 '19 at 13:22
• I'd love to upvote you but unfortunately my reputation is less than 15 – h00man13 Jun 11 '19 at 14:57
• @h00man13 I thought the threshold was 10 – trollingchar Jun 11 '19 at 15:00