- Home /
Unity 2D Platformer: How to properly implement this ground check?
So I've been tinkering away with a 2D player controller and have slowly been making progress. One challenge I've run into is the ground check. The code below is what I have so far. I've removed the other bits of code for movement and jumping just to focus on the ground check.
[Header("Ground Check")]
[SerializeField] bool isGrounded; // Serialized for testing in editor
[SerializeField] LayerMask whatIsGround;
[SerializeField] float groundCheckRaycastDistance;
void Update()
{
GroundCheck();
}
private void GroundCheck()
{
isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckRaycastDistance, whatIsGround) ||
Physics2D.Raycast(new Vector2(transform.position.x - 0.5f, transform.position.y), Vector2.down, groundCheckRaycastDistance, whatIsGround) ||
Physics2D.Raycast(new Vector2(transform.position.x + 0.5f, transform.position.y), Vector2.down, groundCheckRaycastDistance, whatIsGround);
// Draws the raycasts for use in testing
Debug.DrawRay(transform.position, Vector2.down, Color.white);
Debug.DrawRay(new Vector2(transform.position.x - 0.5f, transform.position.y), Vector2.down, Color.white);
Debug.DrawRay(new Vector2(transform.position.x + 0.5f, transform.position.y), Vector2.down, Color.white);
}
This code works perfectly but only because my player is exactly 1 unit by 1 unit in size, so the +/- 0.5 sets the raycasts exactly on the edges of the player.
Is there a way to do this so the raycasts come exactly from the edge of the player without just putting in numbers? Something to do with bounds maybe?
I'm realizing at the time of posting this that I do not need the center raycast, only the left and right raycasts. That's something I will change as well.
https://www.youtube.com/watch?v=c3iEl5AwUF8
3 ways to do a groundcheck in unity
Answer by Marioooo · Sep 01, 2020 at 04:19 PM
Hi! If you're starting on game development i suggest you to start with a rigidbody based character controller son unity can handle the hard stuff for you, if this is not an option then....
Add a child empty gameObject and then place it on character's feet, then simply add a reference for a transform and drag the child to the variable. Also raycast isn't a very performant approach for an update i think... check this live training to see how they implement groundcheck, you'll maybe find something helpful https://www.youtube.com/watch?v=wGI2e3Dzk_w&list=PLX2vGYjWbI0SUWwVPCERK88Qw8hpjEGd8
hope this helps!
Your answer
Follow this Question
Related Questions
Unity ignoring bool grounded 1 Answer
My ground checker only works... sometimes 1 Answer
Jumping when not grounded 2 Answers