Search Unity

C# Help

Discussion in 'Scripting' started by Elinoch, Mar 30, 2017.

  1. Elinoch

    Elinoch

    Joined:
    Mar 28, 2017
    Posts:
    9
    I Need Help Making A Script To Make It So The Player Cant Jump Unless They Are Touching The Ground

    Thanks :)
     
  2. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    What do you have so far?
     
  3. Elinoch

    Elinoch

    Joined:
    Mar 28, 2017
    Posts:
    9

    Code (CSharp):
    1.  if (Input.GetKeyDown("space"))
    2.         {
    3.             GetComponent<Rigidbody>().AddForce(new Vector3(0, 25, 0), ForceMode.Impulse);
    4.         }
    5.         else {
    6.             GetComponent<Rigidbody>().AddForce(new Vector3(0, -1, 0), ForceMode.Impulse);
    7.         }
     
  4. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    Basically what you need to do is, have a bool value that is to track when your character is "grounded" or not. And your gonna want to determine if the character is on the ground or not either by raycasting to the ground, or maybe since your using a rigidbody, you could instead check if the rigidbody is colliding with something marked as ground somehow (either tagged, or the ways its named, or something thats gonna let you know when your colliding with the ground).

    You can find a bunch of stuff to research all this, do some searching on google and the forums for raycast classes if you need it, and one last advice for you, is don't use GetComponent all the time, instead cache a reference in a variable (private Rigidbody rb) and later assign it just once in start or awake method (rb = GetComponent...).