Help With Jump Script - Always Grounded?

Hello Everyone,

I’m new to Unity and am trying to make a 2D game. I’ve been following some tutorials on how to make one of my objects jump. Although, for every attempt, I’m able to keep jumping even when my object isn’t grounded. My goal is to only have this object jump when it is grounded. My main attempts have involved using a Raycast2D, but it seems to always return true. Here is my code so far (C#):

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

	public float Speed = 10f;
	public float JumpAmount = 100f;
	public bool grounded = false;
	

	// Update is called once per frame
	void Update () 
	{
		if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
		{
			transform.Translate ((new Vector3(-Speed, 0, 0)) * Time.deltaTime);
		}
		else if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
		{
			transform.Translate((new Vector3(Speed, 0 , 0)) * Time.deltaTime); 
		}

		if(grounded && (Input.GetKey(KeyCode.W)) || Input.GetKey(KeyCode.Space))
		{
			Jump ();
		}
	}

	void FixedUpdate()
	{
		grounded = Physics2D.Raycast (transform.position, -Vector2.up, -.5f);
	}

	void Jump()
	{
		if(!grounded)
		{
			return;
		}
		grounded = false;
		rigidbody2D.AddForce(Vector2.up * JumpAmount);
	}
}

Any help would be greatly appreciated.
Thanks in advance

What is happening now, is that the raycast detects de player itsself, so it is always grounded. So you need to add a LayerMask, so the raycast doesn’t detect the player.
After adding this it looks like this:

/*Code*/

public LayerMask layerMask;

/*Code*/

void FixedUpdate()
{
     RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 0.5f, layerMask);
     grounded = hit.collider != null;
}

In the editor set the player to another layer (just add new layer “Player” or something) and go to the layermask and select all except the “Player” layermask.

Using characterController you have an yourGameObject.isGrounded bool, just use that for jump checking :wink: