- Home /
inconstant ground check on two identical platforms
so I have two Identical platforms both using a tilemap collider, using the oncollisonenter and exit2d the player is checking for if they are grounded. the player is fine on the first collider but the second collider they arent grounded and both platforms are identical. UPDATE this only happens when i run onto the next platform now when I jump onto it.
Code:
private void OnCollisionEnter2D(Collision2D collisionInfo)
{
if (collisionInfo.collider.tag == "Ground")
{
isGrounded = true;
animator.SetBool("isGrounded", true);
}
}
private void OnCollisionExit2D(Collision2D collisionInfo)
{
if (collisionInfo.collider.tag == "Ground")
{
isGrounded = false;
animator.SetBool("isGrounded", false);
}
}
also im using an edge collider that goes accrose the bottom of the players feet if tht info is helpful at all
Answer by Eno-Khaon · Jul 28, 2020 at 05:25 AM
OnCollisionEnter() triggers only when your character first steps onto a platform. When you step onto an adjacent platform, you will (likely) actively be standing on both of them at the same time.
When you step off of the first platform entirely, and are now standing only on the second platform, you don't have to leave the ground; you're *still* on the second platform, and are no longer on the first. At that time, you will no longer count as "grounded" because you only checked at that one moment.
Luckily, there are multiple solutions to this.
The first, (likely) more robust option is to use OnCollisionStay() instead of OnCollisionEnter(). This way, you'll rapidly verify whether you're on the ground. Then, when you're not on any ground, you will no longer be "grounded".
private void OnCollisionStay2D(Collision2D collisionInfo)
{
isGrounded = true;
}
The second solution should work barring random, bad luck of receiving an unequal number of messages about collisions. By keeping count of the number of active collisions, you should be able to update it only during OnCollisionEnter() and OnCollisionExit() instead.
private int groundedCount = 0;
public bool isGrounded // or private, whatever you were using
{
get
{
return groundedCount > 0; // you're only airborne when 0 (no ground contact)
}
set
{
groundedCount += value ? 1 : -1; // +1 when true, -1 when false
}
}
private void OnCollisionEnter2D(Collision2D collisionInfo)
{
isGrounded = true; // count +1
}
private void OnCollisionExit2D(Collision2D collisionInfo)
{
isGrounded = false; // count -1
}
It may seem a little odd to say isGrounded = false;
and still see it report true (when still in contact with other surfaces), but this approach would allow you to use the same boolean-based formatting, especially when reading the value.
okay with on collision stay its not changing the is grounded when the player jumps, but it does fix the platform changing problem.