Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Need help with a jumping script

Discussion in '2D' started by Prebs, Jan 9, 2015.

  1. Prebs

    Prebs

    Joined:
    Jan 7, 2015
    Posts:
    2
    Right now I'm just playing around in Unity, and trying out different things. I'm not very good with scripting (yet), so i need help to make my character jump.

    The idea is, that the longer you press space (or hold down on a touch screen) the higher the character should jump (with no limits). Holding down longer should make the jump higher.

    If anyone could help me making a such script it would be highly appriciated!
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    Here's something to get you started:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Jump : MonoBehaviour
    5. {
    6.     private bool jumping;
    7.     void FixedUpdate()
    8.     {
    9.         // Are we standing on something, so we can begin jumping?
    10.         bool grounded = Physics2D.Raycast(
    11.             (Vector2)transform.position - Vector2.up * .25f, // .25f is the distance from the pivot point, where we should start looking for the floor
    12.             -Vector2.up,
    13.             0.1f // How far should we look
    14.             );
    15.  
    16.         // Are we standing on something or are we already jumping
    17.         if ((grounded || jumping) && Input.GetKey(KeyCode.Space))
    18.         {
    19.             jumping = true;
    20.             rigidbody2D.AddForce(Vector2.up * 25);
    21.  
    22.             if (rigidbody2D.velocity.y > 200)
    23.             {
    24.                 Vector2 v = rigidbody2D.velocity;
    25.                 v.y = 200;
    26.                 rigidbody2D.velocity = v;
    27.             }
    28.         }
    29.         else
    30.         {
    31.             // If we let go of the jumpbutton, we're not jumping anymore
    32.             jumping = false;
    33.         }
    34.     }
    35. }
    36.  
     
    Prebs likes this.
  3. Prebs

    Prebs

    Joined:
    Jan 7, 2015
    Posts:
    2
    Thank you very much!
    This helped me a lot. Would you mind if I PM you with some questions? :)
     
  4. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    Sure, go ahead.