- Home /
mathf.clamp
Could someone explain what Mathf.Clamp does with an example in his own words(cant get the meaning out of scripting reference)?
Thanks in advance!
Answer by Peter G · Jul 14, 2011 at 12:42 PM
There are two overloaded versions so its slightly different but very similar.
You insert your value.
Give it a minimum
Give it a maximum.
Unity will make sure that your value is never smaller than the min and never larger than the max.
You could write something like this for the same effect.
function Clamp (value : float , min : float , max : float) : float {
if(value < min)
value = min;
if(value > max)
value = max;
return value;
}
so if you clamp between 0 and 5, your value can be any number between those two. So these points are all valid:
value = 3.0
2.3
1.0
0.4
4.9
.000000000001
.02
.49999
but if you try to go above 5 or below 0, then this function will clamp the value at the appropriate min or max.
And the integer version is the same except that the values are all restricted to integers.
Answer by Skjalg · Jul 14, 2011 at 12:38 PM
it basically means that it constraints the value between the min and max.
float value = 10f;
value = Mathf.Clamp(value, 0f, 5f);
print("the value is clamped to: " + value);
//prints 5
Answer by save · Jul 14, 2011 at 12:46 PM
With Mathf.Clamp you set a floor and a roof for a float- or int value. The value can never exceed the negative or positive clamped values.
Example:
//Clamp the Y-value of the Mouse Input to not exceed certain angle when tilting camera
private var ytargetRotation : float = 10;
private var min=-80;
private var max=80;
function Update () {
var yAxisMove : float = Input.GetAxis("Mouse Y")*5;
ytargetRotation+=-yAxisMove;
ytargetRotation=ytargetRotation % 360;
ytargetRotation=Mathf.Clamp(ytargetRotation,min,max);
}
Answer by 123_umer · Oct 10, 2018 at 04:35 PM
the one thing everyone missed was that the value parameter is set in which min and max are defined. so the returning value can range between min and max
yup that exactly what i was looking for ! you made my life easier bro ! (Y)
Your answer
Follow this Question
Related Questions
Mathf clamp movement to Camera space in js 0 Answers
Mathf clamp movement to Camera space in js 1 Answer
Performance of Mathf.Clamp vs if-else statement? 1 Answer
Clamp Rotation Problem 1 Answer
Help clamping a Rotation 1 Answer