Unity 2d jumping script

128,632

Solution 1

Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.

Example:

rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);

Solution 2

The answer above is now obsolete with Unity 5 or newer. Use this instead!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

Solution 3

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

Share:
128,632
user3189504
Author by

user3189504

Updated on June 27, 2020

Comments

  • user3189504
    user3189504 almost 4 years

    Does anyone have a good jumping script for 2d games in unity? The code I have works but still is far from jumping, it looks like it is flying.

    using UnityEngine;
    using System.Collections;
    
    public class movingplayer : MonoBehaviour {
    
    public Vector2 speed = new Vector2(10,10);
    
    private Vector2 movement = new Vector2(1,1);
    
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
        float inputX = Input.GetAxis ("Horizontal");
        float inputY = Input.GetAxis ("Vertical");
    
        movement = new Vector2(
            speed.x * inputX,
            speed.y * inputY);
    
        if (Input.GetKeyDown ("space")){
                             transform.Translate(Vector3.up * 260 * Time.deltaTime, Space.World);
                     } 
    
    }
    void FixedUpdate()
    {
        // 5 - Move the game object
        rigidbody2D.velocity = movement;
        //rigidbody2D.AddForce(movement);
    
    }
    }
    
  • Chris Hawkes
    Chris Hawkes over 4 years
    doesn't do anything for me.