- Home /
Clamping vertical position help
Hello all; I'm addinga gravitatonal force to my player, but I wish to clamp the player from it's position as of when gravity was turned on, and that position.y+15 for example.
Here's what I've got; it doesn't work..
function Update(){
if(Input.GetKeyDown(KeyCode.M) && timer>0.5){
InvertGravity();
}
if(Gravity == true){
transform.position = Vector3(transform.position.x, Mathf.Clamp(0, currentpos.y, currentpos.y+12), transform.position.z);
}
}
function InvertGravity(){
currentpos.y = transform.position.y;
maxpos.y = currentpos.y +10;
if (Gravity == false && timer > 0){
Gravity = true;
timer -=Time.deltaTime;
}
else if(Gravity == true ){
Gravity = false;
}
if (Gravity == true){
timer -= Time.deltaTime;
Debug.Log("whatat");
}
}
Needless to say, i don't quite understand the clamp process =/
Thank you in advance
Answer by Owen-Reynolds · Jan 20, 2013 at 11:22 PM
As an alternative, just don't use clamp. Clamp is a teeny, tiny trick that does nothing magical at all. The main reason Unity has it is that people with a math or graphics card background use "clamp" as a technical term. It doesn't even make your program run faster.
All clamp does is a pair of Ifs. Say you want pos.y
to never get above cur.y+12, write: if(pos.y>cur.y+12) pos.y=cur.y+12;
If you want to never dip below cur.y-12, write the opposite IF. Clamp is merely those two ifs in a row (maybe with an else.)
Answer by FL · Jan 20, 2013 at 06:09 PM
Mathf.Clamp(A, B, C) generally returns B. Returns A if A > B. Return C if C < B.
Examples:
Mathf.Clamp(5, 7, 10) returns 7.
Mathf.Clamp(5, 1, 10) returns 5.
Mathf.Clamp(5, 11, 10) returns 10.
Mathf.Clamp(0, currentpos.y, currentpos.y+12) always returns currentpos.y or 0 if currentpos.y<0, but never currentpos.y+12 because currentpos.y+12
Your answer
Follow this Question
Related Questions
How to limit the rotation of an object?? 2 Answers
gesture rotation clamp 2 Answers
MathF clamp not working 1 Answer
Mathf.Clamp is not Clamping. 1 Answer
Swipe movement limitation 2 Answers