- Home /
How to check if BoxCollider2D collided with another BoxCollider2D?
I have a player and an enemy. The player has a BoxCollider2D and so does the enemy. How can I check if the player's BoxCollider2D collided with the enemy’s BoxCollider2D?
Answer by PersianKiller · Sep 17, 2017 at 06:44 AM
you can use OnTriggerEnter2D function.
for example I attached this script to a bomb,if player collides with it ,it Will explode.
void OnTriggerEnter2D(Collider2D other){
if (other.name == "player") {
Destroy (other.gameObject);
}
}
you can also check it like this
void OnTriggerEnter2D(Collider2D other){
if (other.name == "player") {
// playerCollides with the Enemy
}
}
and for exit
void OnTriggerExit2D(Collider2D other){
if (other.name == "player") {
// player is not colliding with the Enemy anymore
}
}
but at least one of your objects should have a Rigidbody2D component and at least of of BoxCollider2Ds should be trigger.
and if your colliders should not be trigger you can use
OnCollisionEnter2D(Collision2D other){
}
Answer by bananatrooper52 · Sep 17, 2017 at 08:10 AM
Check the official Unity documentation on this, it has almost exactly what you're asking for.
Your answer
Follow this Question
Related Questions
Don't Flip Child, Only Parent. 0 Answers
How can I move my BoxCollider2D ? 1 Answer
Jumping isn't smooth while going up 1 Answer
Flip Player, but don't flip the Player's Child. 2 Answers
Flip Player, Not the Player's Child. 3 Answers