Mathf.Clamp with the rigidbody

Hi guys, in this script if you press Q the object goes up, instead if you press E, it goes down. but it should have limits for both (max hight and minimum down position). I sow that I have to use Mathf.Clamp to set the limits, but in the unity API ther’s an example with “transform.position”, I don’t have It in my script. Where Can I put The Mathf.Clamp limits in my script?
Thank you and happy holidays to everyone :slight_smile:

#pragma strict

	
	var GoUp = 1.0;
	var GoDown = 5.0;

   function FixedUpdate() {
   
   if (Input.GetKey(KeyCode.Q)) {
      GetComponent.<Rigidbody>().AddForce(transform.up * GoUp);
   }
   else if (Input.GetKey(KeyCode.E)) {
      GetComponent.<Rigidbody>().AddForce(-transform.up * GoDown);
   }
   else if (Input.GetKey(KeyCode.W)) {
      GetComponent.<Rigidbody>().velocity = GetComponent.<Rigidbody>().velocity * 0.9;
   }
}

The clamp function restricts the value of something to be between two values. In your case, you need to restrict your y position, so you need to firstly define two floats (ymin, ymax) and add a check in your code that your rigidbody’s y position is within this range. You could do this without a clamp function - have an if statement that checks the rigidbody’s y position, and if it is outside of this range, set the velocity in either the up or down direction to be zero. Otherwise, just before you end your FixedUpdate function I think adding a line a bit like this;

transform.position.y = new Vector3(Mathf.Clamp(transform.position.y, ymin, ymax), 0, 0);

might do the trick, but have not tested it.