Ground Check with a Ray
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 37 of 71.
A jump should start only from the ground. Standing on the Ground worked that out from contact normals, kept up to date by collision messages. A ray answers "am I standing on something?" on the spot, at any moment: cast it straight down from the centre, a little longer than the distance from the centre to the bottom. This player is a capsule 2 units tall, so its bottom is 1 unit below its centre, and the ray is 1.1 long:
public float jumpForce = 5f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
bool IsGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, 1.1f);
}The extra 0.1 is a margin. A body resting on the floor can sit a hair above it or sink a hair into it, so a ray exactly 1 long misses on some frames. Much longer is wrong the other way: with 3, the player could jump again 2 units up in the air, and with no length at all the ray always finds the floor, so every press is a jump.
The ray starts inside the player's own collider, which rays skip, so it never reports the player. The key is read in Update(), because GetKeyDown is true for one frame only, and a one-off impulse can be added right there, as in Jump with an Impulse.
Challenge
MediumLet the frog jump only from the ground.
- Add
bool IsGrounded()that returnsPhysics.Raycast(transform.position, Vector3.down, 0.85f): the frog's radius, 0.75, plus 0.1. - In
Update(), add&& IsGrounded()to theifon Space.
Press Play and press Space twice: the frog jumps once. Then Check.
Try it yourself
using UnityEngine;
public class Hopper : MonoBehaviour
{
public float jumpForce = 6f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground