- Home /
Player grounder cheacker
I want to know if my player is on the ground or not. I made a little box collider 2d on the bottom of his feet with the tag "groundchecker". How do I know if that collider is currently touching somthing? The box collider is a child of the player. I am writing in C#.
Thank you for the answers :D.
Answer by kevojo · Sep 24, 2018 at 06:52 AM
GameObject player; // initialize this in Start - player = this.gameobject;
public LayerMask IgnorePlayer;
private void CheckForGroundCollision()
{
Vector3 GroundCheckStartPoint = new Vector3(player.transform.position.x, player.transform.position.y + 1f, player.transform.position.z);
RaycastHit hit;
if (Physics.SphereCast(GroundCheckStartPoint, .5f, Vector3.down, out hit, 1.1f))
{
if (hit.collider.tag == "ground")
{
isGrounded = true;
}
else
{
isGrounded = false;
}
}
else
{
isGrounded = false;
}
}
I think this code is a little bit wordy, I'd personally refactor it to remove that inner else statement, but that's just me. You should also watch your na$$anonymous$$g convention, it's a bit inconsistent. Here's how I would write it:
public bool isGrounded { get; private set;}
private void CheckForGroundCollision()
{
var groundCheckStartPoint = transform.position + Vector3.up;
var groundLayer = Layer$$anonymous$$ask.Get$$anonymous$$ask( "Ground" );
RaycastHit hit;
isGrounded = Physics.SphereCast( groundCheckStartPoint, 0.5f, Vector3.down, out hit, 1.1f, groundLayer );
#IF DEBUG
if ( hit.collider.tag != "ground" )
Debug.LogWarning( "Something is incorrectly placed on the ground layer. This will prevent the player from finding the ground." );
#ENDIF
Your answer
![](https://koobas.hobune.stream/wayback/20220612175127im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Is Triggered Collider Issue 1 Answer
Lose health on collision 1 Answer
Play animation when colliding with trigger! 3 Answers
On Collide script not working! 1 Answer
My Player keeps launching into the air 4 Answers