- Home /
OnCollisionEnter2D and OnCollisionExit2D
For some reason I can't figure out how to get OnCollisionEnter2D &Exit2D to work.I have attached a small hitbox to the bottom of my character in a child but it seems to not be able to check when it hits the ground and when it exits. It stays in one state and when you hit a corner it goes berzerk. My main aim is for it to not be able to double or triple jump. I have the parent script check if the variable isGrounded is true or false and jump accordingly.The parent script is called Move2D if you need it.
Any help would be greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grounded : MonoBehaviour
{
GameObject Player;
// Start is called before the first frame update
void Start()
{
Player = gameObject.transform.parent.gameObject;
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter2D(Collision2D Collision){
if(Collision.collider.name == "Ground_1"){
Debug.Log("Hit with ground");
Player.GetComponent<Move2D>().isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D Collision){
if(Collision.collider.name == "Ground_1"){
Debug.Log("Left the ground");
Player.GetComponent<Move2D>().isGrounded=false;
}
}
}
Answer by BradyIrv · Feb 26, 2020 at 10:30 AM
When you say it doesn't work, do you mean it's not registering any debug logs to the console? Does your player have a Rigidbody2D attached to it?
I usually use small trigger spheres since it's a bit more reliable than just registering the collision of the player with the ground. If the Sprite is a bit jumpy for any reason, collision enter/exit will run multiple times.
Otherwise it might be better to use another method for your ground check. For example have an empty object on your player at the feet and use Physics.OverlapSphere from that points position.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Jumping: Endless Runner,Hey can anyone help with this endless runner script ? 1 Answer
Advanced jumping 0 Answers