Jump script

Hello, I saw this script some where about 1/2 weeks back can’t remember where tho, I’ve edit it abit. The problem i’m having atm with the code is when i jump it doesn’t understand its touch the “Ground” again there like a little delay or lots of spamming to fix it. (The tag i’m using for the ground tag is “grounded” if you can help me it will be great help Script i am using can be found below.

Thank you very much

Luke

using UnityEngine;
using System.Collections;

public class Jump : MonoBehaviour {
    public bool grounded = true;
    public float jumpPower = 1;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if(!grounded && GetComponent<Rigidbody>().velocity.y == 0) {
            grounded = true;
        }
        if (Input.GetButtonDown("Jump") && grounded == true) {
            GetComponent<Rigidbody>().AddForce(transform.up*jumpPower);
            grounded = false;
        }
    }


}

I opted for writing my own isGrounded function, using raycasting to find distance to ground to return a bool. Only need to use it when “jump” is being pressed. My primary reason for doing so was that I could find 0 information on the CharacterController.isGrounded

You can use a raycast condition to check if grounded

it casts a very small ray, directly below the player/GO and checks if it hits anything

float dist;

public bool checkGrounded()
{
  return Physics.Raycast(transform.position, -Vector3.up, dist + 0.1f);
}

then if you want to call the code, use

if (Input.GetButtonDown("Jump" && checkgrounded)
{
// jump
}
if (Input.GetButtonDown("Jump") && checkGrounded)
{
// jump
}

Minor correction to the code.

But what Rob laid out is exactly what I was meaning. Mine is a bit more complicated, since I’m checking for what the collision tag is.
You can also replace -Vector3.up with Vector3.down
I never really understood why people are constantly using negative up instead of down.

1 Like