# I need help with 2d character jumping

I am having difficulty getting my character to jump correctly. He will jump, but I need him to only jump while on the ground.

Here is my code:

using UnityEngine;
using System.Collections;

public class CharMove : MonoBehaviour
{

``````public float speed = 20.0f;
public int jumpHeight = 50;
public bool isGrounded = false;

void Update ()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.Space) && isGrounded == true)
{
jump();
}
}

void jump()
{
if(!isGrounded)
{
return;
}
isGrounded = false;
}

void FixedUpdate()
{
isGrounded = Physics2D.Raycast(transform.position, -Vector2.up);
}
``````

}

Hi I did some changes to your script. I created a game object where I added an edge collider. Why? So I can have a reference to the ground .

``````public float speed = 20.0f;
public int jumpHeight = 50;
public bool Grounded = false;
public Collider2D floor; //Here will be the GO that references the ground

void Update ()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.Space) )
{
jump();
}
}

void jump()
{
if (Grounded == true)
{
GetComponent<Rigidbody2D> ().AddForce (new Vector3 (0, jumpHeight, 0), ForceMode2D.Force);
Debug.Log("Entro cuando true");
}
else
{

}
}

void FixedUpdate()
{
//isGrounded = Physics2D.Raycast(transform.position, -Vector2.up);
isGrounded ();
}

void isGrounded()
{
if (GetComponent<Collider2D> ().IsTouching (floor)) {
Grounded = true;
} else
{
Grounded = false;
}
}
``````