Jumping issues [2D]

I’m a complete beginner to coding but I’m working on a game in 2D where you’re a square. Now it’s very small and I just started working on the square’s movement script…

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {
    public float speed = 1F;
    public float jump = 1F;

    void Start () {
  
    }
  
    void Update () {
        if (Input.GetKey(KeyCode.D))
            transform.position += new Vector3(speed + Time.deltaTime, 0F, 0F);
        if (Input.GetKey(KeyCode.A))
            transform.position -= new Vector3(speed + Time.deltaTime, 0F, 0F);
        if (Input.GetKey(KeyCode.Space))
            GetComponent<Rigidbody>().AddForce(new Vector2(0, 1), ForceMode.Impulse);
    }
}

How do I make it so that this doesn’t just jump whenever I hit spacebar? I don’t understand how to make it check at all so if you guys could give me just an edited, fully working version of my script, that would be amazing. Thanks in advance!

Using Unity 5 so please nothing that will be obsolete!

Everybody can’t go around just writing scripts for beginners or they wouldnt get any of their own work done :stuck_out_tongue:

Anyway what YOU should try to achieve is this. Get a way to detect if your player is on the ground. Like for instance if your level has colliders you can just do raycasting from the player “down” to hit with the level, and if nothing at a certain distance is hit, you know your not “grounded” at the time. Then as you check for input before allowing a jump, you also check if your grounded, and only allow the character to jump if the key is pressed AND the character is grounded.

Your code might end up like:

Plus, if you figure that out on your own, you shall gain a better ability to help yourself in the future :slight_smile: