- Home /
 
The question is answered, right answer was accepted
Mathf.Clamp issues
Hi there, so i have a script for camera movement/control and it was giving me issues related to a clamp it was going beyond the boundaries and returning to the position instead of just clamp, so i decided to do a new script more simple, and it's doing the same.
Previous problem: The other script which is more advanced and better done have those problems too.
Problem: If you use this script in a camera and move fast the mouse to down or up it will go beyond the clamp and then return to the clamp.
 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
  
 public class MouseLook2 : MonoBehaviour{
 
     Vector2 mouseDelta;
     Vector3 absolutePosition;
     Vector3 finalRotation;
     Vector3 smoothedPosition;
 
 
     public Vector2 yLimit = new Vector2(-75,150);
     public Vector2 sensitivity = new Vector2(2, 2);
     public GameObject characterBody;
 
     public void LateUpdate(){
 
     mouseDelta = new Vector2 (Input.GetAxisRaw ("Mouse X"), Input.GetAxisRaw ("Mouse Y"));
         
 
         //Add inverted mouse delta value of Y (If we want inverted view just delete the negative sign)
         absolutePosition.x = -mouseDelta.y;
         //Add Mouse delta value of X
         absolutePosition.y = mouseDelta.x;
 
         finalRotation = absolutePosition;
         finalRotation = new Vector3(Mathf.Clamp(finalRotation.x,-yLimit.y,-yLimit.x),0,0);
         transform.localEulerAngles += finalRotation;
 
     }
 
 
 }
 
               Thanks in advanced.
When dealing with rotations I would suggest you read up on how to use Quaternions. Also for smoothing look up Lerp and Slerp.
What @awest said is at least one of the problems.
You're limiting how much the camera rotation can change in one LateUpdate() but not it's max rotations.
@awest and @Nose$$anonymous$$ills
transform.localEulerAngles += finalRotation; transform.localEulerAngles = new Vector3($$anonymous$$athf.Clamp(transform.localEulerAngles.x,-yLimit.y,-yLimit.x),0,0);
Got it working, thanks a lot, i think both of you should put the comment as answer so i can accept it, thanks a lot ^^!
@$$anonymous$$ayelGee thanks a lot to you too sir ^^!
Answer by awest · Oct 10, 2014 at 03:46 AM
Thanks @NoseKills @KayelGee. I had to go to work. Glad you were able to see it through.
The problem was this line because it added a clamped value to an unrestricted variable.
 transform.localEulerAngles += finalRotation;
 
               It was fixed by being changed to the following line.
 transform.localEulerAngles = new Vector3(Mathf.Clamp(transform.localEulerAngles.x,-yLimit.y,-yLimit.x),0,0);
 
               I've never done one of these past-tense. It feels weird.