@script RequireComponent(CharacterController) // Movement variables. var jumpSpeed : float = 0.4; var gravity : float = 1; //Init movement variables. private var movement = Vector3.zero; private var grounded : boolean = true; private var jumping : boolean = false; //Init controller variables. private var controller : CharacterController; private var collisionFlags : CollisionFlags; function Update() { var controller : CharacterController = GetComponent(CharacterController); // Make jump when jump button is pressed and we're on the ground. // Jump button is spacebar. if ((Input.GetButtonDown("Jump")) && IsGrounded()) { // Check we're not already jumping... // ...we don't want to let you jump in mid-air. if (!jumping) { jumping = true; grounded = false; movement.y = jumpSpeed; } } //Are we jumping? if (jumping) { // Are we moving up and have hit our head on something? // Then stop moving up. if ((IsHitAbove()) && (movement.y > 0)) { movement.y = 0; } // Are we moving down and have landed on something? // Then set us as grounded and not jumping. if ((IsGrounded()) && (movement.y < 0)) { jumping = false; grounded = true; } } //Are we standing on something and not jumping? //Then zero down speed - needed for correct gravity if you fall off something... //...otherwise gravity keeps building up and you fall to the ground instantly. if ((IsGrounded()) && (grounded)) { movement.y = 0; } // Apply gravity. movement.y -= gravity * Time.deltaTime; // Move the character. collisionFlags = controller.Move(movement); } // Func to check if we've hit anything below us. function IsGrounded() { return (collisionFlags & CollisionFlags.CollidedBelow) != 0; } // Func to check if we've hit anything above us. function IsHitAbove() { return (collisionFlags & CollisionFlags.CollidedAbove) != 0; }