Jumping Ball

Im trying to get my ball to jump but sometimes it just doesnt jump. The boolean turns it self off when hitting the spacebar but doesnt jump and stays on the ground. Here’s my script.

bool canJump = false;
void OnCollisionEnter(Collision other)
	{
		if (other.gameObject.tag == "ground") {
			canJump = true;
			Debug.Log("test");
		}
	}
	void Movement()
	{

		move = Input.GetAxis ("Horizontal");
		rigidbody.velocity = new Vector3 (move * 5f, rigidbody.velocity.y);
		
		if(Input.GetKeyDown("space"))
		{
			if(canJump)
			{
			rigidbody.AddForce(new Vector3(0,10),ForceMode.Impulse);
				canJump =false;
			}

		}
	}

A reliable way to code jumping is to cast a ray downwards for a short distance and see if it hits the ground.

The code that you have assumes that whenever you press the jump key, you leave the collision with the ground, and after some time, you will enter collision again, triggering OnCollisionEnter. This isn’t always true though.

If you press the jump key but don’t leave collision with the ground, then you won’t enter collision with the ground, meaning that canJump won’t be set to true even if you’re on the ground. For example, if you try to jump, but you’re blocked by a ceiling and don’t actually leave the ground, you won’t be able to jump anymore. (This is definitely a problem that can happen in your code, but I’m not sure if it’s the problem that you’re having right now.)

The general raycasting idea is to use Physics.Raycast with a ray from your player’s position downwards, setting maxDistance appropriately so that the ray ends at the bottom of your player. This ray should ideally collide with the ground only when your player is touching the ground.

When you press the jump key, set some boolean isInAir to true. Whenever isInAir is true, perform the raycast, and if the ray hits the ground, set isInAir to false.