Hello,
i am trying to make my character jump only when touching the ground … i use c#
any help would be appreciated… thank you
If your character is a CharacterController, use the property isGrounded:
public float speed = 6; public float jumpSpeed = 8; CharacterController cc; float vVel = 0; void Start(){ cc = GetComponent< CharacterController>(); } void Update(){ // get movement direction relative to the character: Vector3 vel = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); vel = transform.TransformDirection(vel)*speed; // convert to world space // only jump when the character is grounded: if (Input.GetButtonDown("Jump") && cc.isGrounded){ vVel = jumpSpeed; } vVel -= gravity * Time.deltaTime; // apply gravity vel.y = vVel; // combine vertical and horizontal velocities cc.Move(vel * Time.deltaTime); // move the character }
But if your character is a rigidbody, you must check if it’s grounded - a raycast downwards is a good alternative:
public float speed = 6; public float jumpSpeed = 8; float height; // raycast length void Start(){ rigidbody.freezeRotation = true; // calculate height from ground plus a little margin (0.2) height = collider.bounds.extents.y + 0.2f; } void FixedUpdate(){ // get movement direction relative to the character: Vector3 vel = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); vel = transform.TransformDirection(vel)*speed; // convert to world space vel.y = rigidbody.velocity.y; // keep rigidbody's vertical velocity // only jump when the character is grounded: if (Input.GetButtonDown("Jump") && Physics.Raycast(transform.position, Vector3.down, height)){ vel.y = jumpSpeed; } rigidbody.velocity = vel; }