Search Unity

Jump script

Discussion in 'Scripting' started by Luke3671, Sep 8, 2016.

  1. Luke3671

    Luke3671

    Joined:
    Jul 6, 2014
    Posts:
    56
    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

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Jump : MonoBehaviour {
    5.     public bool grounded = true;
    6.     public float jumpPower = 1;
    7.     // Use this for initialization
    8.     void Start () {
    9.  
    10.     }
    11.  
    12.     // Update is called once per frame
    13.     void Update () {
    14.         if(!grounded && GetComponent<Rigidbody>().velocity.y == 0) {
    15.             grounded = true;
    16.         }
    17.         if (Input.GetButtonDown("Jump") && grounded == true) {
    18.             GetComponent<Rigidbody>().AddForce(transform.up*jumpPower);
    19.             grounded = false;
    20.         }
    21.     }
    22.  
    23.  
    24. }
     
  2. Vedrit

    Vedrit

    Joined:
    Feb 8, 2013
    Posts:
    514
    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
     
  3. Rob21894

    Rob21894

    Joined:
    Nov 21, 2013
    Posts:
    309
    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

    Code (CSharp):
    1. float dist;
    2.  
    3. public bool checkGrounded()
    4. {
    5.   return Physics.Raycast(transform.position, -Vector3.up, dist + 0.1f);
    6. }
    then if you want to call the code, use

    Code (CSharp):
    1. if (Input.GetButtonDown("Jump" && checkgrounded)
    2. {
    3. // jump
    4. }
     
  4. Vedrit

    Vedrit

    Joined:
    Feb 8, 2013
    Posts:
    514
    Code (CSharp):
    1. if (Input.GetButtonDown("Jump") && checkGrounded)
    2. {
    3. // jump
    4. }
    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
    Code (csharp):
    1. -Vector3.up
    with
    Code (csharp):
    1. Vector3.down
    I never really understood why people are constantly using negative up instead of down.
     
    ajaykewat likes this.