- Home /
how do i check if my rigidbody player is grounded?
how do i check if my player is grounded?, because its kinda annoying how my player can jump in mid air. this is the script im using, its in javascript:
var jumpSpeed: float = 8;
function Update () {
if (Input.GetKeyDown (KeyCode.Space)){
rigidbody.velocity.y = jumpSpeed;
}
}
@aldo - 3,000+ views on this question in two weeks! Strange isn't it? It's impossible to guess what will be wildly popular!!
happy new year!
Answer by aldonaletto · Dec 18, 2011 at 03:45 AM
You could do a short Raycast in the down direction to check if the ground is there. "short" in this case means the distance from the player pivot to the ground (distToGround); in most cases, collider.bounds.extents.y is this distance (unless collider.bounds.center isn't 0,0,0). It's advisable to add a small margin (say, 0.1) to compensate for small ground irregularities or inclination:
var distToGround: float;
function Start(){
// get the distance to ground
distToGround = collider.bounds.extents.y;
}
function IsGrounded(): boolean {
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1);
}
function Update () {
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded()){
rigidbody.velocity.y = jumpSpeed;
}
}
Answer by Setsuki · Dec 04, 2012 at 05:13 PM
Aldo Naletto's idea's really good, I've been using this in my game for about 2 months. But there's one small flaw. If the ground is a bit uneven, it doesn't really work. "I'll cast the ray further then" was my first idea, but what if it's a hole? What is needed is a capsulecast instead of a raycast:
//collider.bounds are the bounds collider relative to the world. I wanted a 0.1 margin, and 0.18 is the radius of my collider.
Physics.CheckCapsule(collider.bounds.center,new Vector3(collider.bounds.center.x,collider.bounds.min.y-0.1f,collider.bounds.center.z),0.18f));
I was gonna go down the route of raycast like the thirdpersoncontroller in standard assets, but you just led me to Physics.CheckBox which is perfect for my case!
Hi i am also using this for detecting my ground, i have the problem with the uneven ground thing, so how do you solve this? ...
The way it's presented currently means it would check if there is a collider within the volume between the player's collider and the player's bottom, wouldn't that always be true?
Is there a way to get this to ignore the attached collider?
@smallville7123 There is a Physics.CheckSphere() method if you are using a sphere. Please look at the documentation: https://docs.unity3d.com/ScriptReference/Physics.CheckSphere.html
@EzrAbl42 You can provide a layer mask to the method, which will allow you to exclude your player character's collider.
Answer by arvind53 · Jun 01, 2012 at 12:46 PM
var isgrounded : boolean = true;
function Update()
{
if(isgrounded == true)
{
//Do your action Here...
}
}
//make sure u replace "floor" with your gameobject name.on which player is standing
function OnCollisionEnter(theCollision : Collision){
if(theCollision.gameObject.name == "floor")
{
isgrounded = true;
}
}
//consider when character is jumping .. it will exit collision.
function OnCollisionExit(theCollision : Collision){
if(theCollision.gameObject.name == "floor")
{
isgrounded = false;
}
}
this works for me quiet well.....
This worked for me as well! Been searching for a script that tells unity that my character left the ground. Now I can stop my character from jumping infinitely! Thank you!
Now if only I can change the speed at which he goes up and comes down, without sending the character shooting for the stars..
I tried this but I found it too unreliable. Even if I set the sleeping mode to "Never sleep" OnCollisionExit sometimes fails to fire for some reason (I think). This causes my player to suddenly learn to fly...
$$anonymous$$y script was a bit modified, though. Ins$$anonymous$$d of a boolean used a counter to keep track of how many objects of the "floor" type the player is colliding with (I have multiple platforms ins$$anonymous$$d of just one "floor").
If you find the OnCollisionExit to be too unreliable, Add "isGrounded = false;" to your jump code as well. So, unless something aside from jumping throws you into the air, you are covered.
but then if player not stand on a "floor" its not grounded?
In my game, using the OnCollisionEnter/ OnCollisionExit approach led to an annoying behavior where if the collision detection box for the ground check left the space of one ground object while still in the space of another ground object (imagine the border between two flush rectangular platforms) it would activate the OnCollisionExit method, despite my character being grounded. I am unsure how to avoid this behavior, so I will be using the Physics.CheckCapsule approach ins$$anonymous$$d.
Answer by NathanJSmith · Aug 30, 2018 at 08:37 AM
Why don't use Unity's OnCollisionStay function?
I've used "Raycast down" method like aldonaletto suggested but it causes issue when player stand on an edge and the raycast miss the edge.
Understand how OnCollisionStay works
With OnCollisionStay, you can accurately detect the ground. Here is how OnCollisionStay works:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
void OnCollisionStay(Collision collisionInfo)
{
// Debug-draw all contact points and normals
foreach (ContactPoint contact in collisionInfo.contacts)
{
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
}
}
Attach the script above to your character (your character has CapsuleCollider component), then run the game, look at your character in Scene widow instead of Game Window (because Debug.DrawRay
only works in Scene window), you should see a white ray where the character touches things.
Implement the idea
//----------PlayerCollider.cs------------
public class PlayerCollider : MonoBehaviour
{
private bool m_IsOnGround;
public bool IsOnGround
{
get
{
if (m_IsOnGround)
{
m_IsOnGround = false;
return true;
}
else
{
return false;
}
}
}
void OnCollisionStay()
{
//If it touch things, then it's on ground, that's my rule
m_IsOnGround = true;
}
}
//----------Player.cs------------
public class Player : MonoBehaviour
{
PlayerCollider m_playerCollider;
void Start()
{
//...
m_playerCollider = GetComponent<PlayerCollider>();
}
void Update()
{
if (m_playerCollider.IsOnGround)
{
Debug.Log("On Ground");
}
else
{
Debug.Log("In air");
}
}
}
Want a working example out of the box?
Check this free asset: Ragdoll and Transition to Mecanim (the time I write this answer, the asset is free, guess it will still be free by the time you check it)
The character controller in the asset above uses OnCollisionStay to detect ground.
Answer by sloopernine · May 12, 2013 at 05:17 PM
Is it possible to get aldonaletto´s answer translated into c# ?
I tried to translate it right off but that didnt help. I am new to java and c# so please dont flame me.
I did this but get some errors like:
Operator &&' cannot be applied to operands of type
bool' and UnityEngine.Vector3' The best overloaded method match for
UnityEngine.Physics.Raycast(UnityEngine.Vector3, UnityEngine.Vector3, float)' has some invalid arguments
Argument #3' cannot convert
double' expression to type `float'
// Jump variable
private float distToGround;
if(jump_key && IsGrounded())
{
Jump();
}
void Start ()
{
//Get the distance to ground.
distToGround = collider.bounds.extents.y;
}
void Jump()
{
rigidbody.AddForce(Vector3.up * jumpForce);
animation.Play("jump_pose");
}
void IsGrounded()
{
return Physics.Raycast(transform.position, - Vector3.up, distToGround + 0.1);
}
in C#, you can change a double (0.5) into a float by adding f. so you want to change your line return Physics.Raycast(transform.position, - Vector3.up, distToGround + 0.1); into return Physics.Raycast(transform.position, - Vector3.up, distToGround + 0.1f);
Also, your "if(jump_key..." isn't in any function or method, so it won't compile either. change it to void Update() { if(jump_key && IsGrounded()) { Jump(); } }
Also, your IsGrounded method returns a vector3, it should return a bool. Finally, I'm sorry, but you'll have to stop posting your problems on a non-relative thread. I also advise you to search for your errors before posting on a forum, because you'll lose a lot of time if you ask for help every time you get a cast error.
Yeah I figured that out, and you are right. so thats why I deleted the post again. But not fast enough as you were quicker to answer it. Thanks again and sorry mate :D
"I'm sorry, but you'll have to stop posting your problems on a non-relative thread."
This is actually the first results when Googling "unity C# check if grounded"; So he's probably not the only person whom was wondering this.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
WheelColliders Bug Fix 0 Answers
custom rigidbody movement problem 2 Answers
Get player pulled to position/object 1 Answer
if moving statement 1 Answer