- Home /
C# How to check if player is grounded?
How do I convert this to C#?
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;
}
}
//consider when character is jumping .. it will exit collision. function OnCollisionExit(theCollision : Collision){ if(theCollision.gameObject.name == "floor") { isgrounded = false; } }
Answer by tmalhassan · Oct 08, 2017 at 04:57 PM
Hello @watercolorheartdev. Try this:
bool isgrounded = true;
void Update()
{
if (isgrounded == true)
{
//Do your action Here...
}
}
//make sure u replace "floor" with your gameobject name.on which player is standing
void OnCollisionEnter(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = true;
}
}
//consider when character is jumping .. it will exit collision.
void OnCollisionExit(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = false;
}
}
Hope this helps :)
Thanks, but your code has an error... The void where u make the isgrounded false has to be like this if (theCollision.gameObject.name != "floor")
Still tho, this helped a lot :)
Hey there @$$anonymous$$arxmon. I only converted the script from JS to C#. The code is correct tho. What it does is check if there is collision with the object with the name "floor". If there is collision with it, that means the player is grounded. Else, when it exits the collision, the player is not grounded.
If anyone is looking at this now, Marxmon's comment is not correct, because this would set isGrounded to false whenever the player stops touching something that is not the ground, rather than whenever they stop touching the ground
Awesome! Simple solution, but works really good. Thanks!
I tried this solution, and for some reason it caused the character to speed up in free fall when the WASD or arrow keys are pressed. Any idea why this is?
For those who are designing in 2D, make sure to use OnCollisionExit2D and OnCollisionEnter2D. Also Collision should be Collision2D