How do I jump?

Hi. I am trying to make a cube jump. It works with this code:

function FixedUpdate () {
    if (Input.GetButtonDown ("Jump")) {
        rigidbody.velocity.y = 10;
    }
}

(I got it from the scripting reference)
But I only want it to jump when it’s grounded. How do I do that :?:

Try doing OnCollisionStay instead of FixedUpdate.

function OnCollisionStay () { 
    if (Input.GetButtonDown ("Jump")) { 
        rigidbody.velocity.y = 10; 
    } 
}

Or, in case your character might be bounced off the ground every few frames, totally messing up the collision thing, you could use a raycast, like this:

function FixedUpdate () { 
   var hit : RaycastHit;
   var down = transform.TransformDirection (Vector3.down);
   if (Physics.Raycast (transform.position, down, .5)) {
      //Our cube is within a close enough range of the ground to jump
      if (Input.GetButtonDown ("Jump")) {
        rigidbody.velocity.y = 10;
      }  
   }
}

You’d probably have to change the distance of the ray from .5 to whatever works best for your game. :slight_smile: Good luck!

Thanks Moldorma :smile: ! That helped.

:slight_smile: Any time!