- Home /
Detecting when player isn't grounded when the ground disappears?
I'm making a 2D platformer and I have platforms that disappear when the player stands on it. To detect wether the character is grounded I use OnCollisionStay2D and OnCollisionExit2D. The problem is that OnCollisionExit2D doesn't fire when the platform disappears. I'm trying to find a way to always detect the player's collision, even if it isn't colliding with anything. That way if it isn't colliding with anything I could detect that. Is there anyway to do that? Or to make OnTriggerExit2D fire when the object is disabled? This is the relevant code: //The solution I'm trying to implement void OnUpdate() { foreach(ContactPoint2D contact in rb.GetComponent().contacts) { if(contact.normal == new Vector2(0, 1)) { print("grounded"); } } }
//The Ground detection. This works fine except for the case mentioned above
private void OnCollisionStay2D(Collision2D collision)
{
foreach (ContactPoint2D contact in collision.contacts)
{
if (contact.normal == new Vector2(0, 1))
{
isGrounded = true;
break;
}
else
{
isGrounded = false;
}
}
}
private void OnCollisionExit2D(Collision2D collision)
{
isGrounded = false;
}
Answer by Relan42 · May 03 at 12:36 AM
I found a solution. Here it is for anyone who is curious. //Get the contacts the player is touching private void OnCollisionStay2D(Collision2D collision) { contacts = collision.contacts; }
//checks the number of contacts. If the number is 0 it means it isn't touching anything
void Update()
{
if(contacts != null)
{
if (rb.GetContacts(contacts) == 0)
{
touchesLeftWall = false;
touchesRightWall = false;
isGrounded = false;
}
}
}
Your answer
Follow this Question
Related Questions
Trigger not being activated? 1 Answer
How to check from which side a gameobject collide? 0 Answers
2D 360 degress platformer example needed 0 Answers
Using GetComponent to get a script 1 Answer