- Home /
Need Extremely Specific Collision Detection (2D)
So what I want to have happen is that when a bullet hits the player, the level resets as the player is effectively killed. However, there is a child of the player with a totally different tag ("Deflector") that, when hit, should not result in a level reset. The problem is I am not sure how to get the game to check the tag of the child object so that when it hits the main player, it's a kill, but when it hits the deflector, nothing happens.
The code looks like this. void OnCollisionEnter2D(Collision2D Other) { if (Other.gameObject.tag == "Player") { Application.LoadLevel(Application.loadedLevel); } }
Answer by Tanshaydar · Oct 10, 2014 at 12:46 PM
Instead of checking only player, you can check each part respectively with if-else statements. Game objects with colliders will check any collider regardless of their parents and/or children.
void OnCollisionEnter2D( Collision2D other) {
if (Other.gameObject.tag == "Head") { // This is the head collider, headshot
Application.LoadLevel(Application.loadedLevel);
}
else if (Other.gameObject.tag == "Deflector") { // This is the deflector collider,
//have player health drop here
}
else if (Other.gameObject.tag == "Other Body Parts") { // This can be multiple body parts
// have player health drop here
}
}
I'd personally suggest using trigger colliders instead of physic colliders, and use OnTriggerEnter2D. However, that's up to you and your game design.
Answer by EmpI · Oct 10, 2014 at 05:42 PM
The nested else if statements didn't work, for reasons I can't imagine. However you did suggest using triggers instead. The Deflector absolutely must use collisions, but the player's collider isn't that sacred even though I do still want one. With this in mind, I removed the deflector from a collision statement entirely (after a bit of experimenting it wasn't completely necessary to have a collision2D statement where, after the If statement it did absolutely nothing) and put the player sphere in an OnTriggerEnter2D statement.
In other words, everything works now, thanks for your help!
Your answer
Follow this Question
Related Questions
Collision with tag 5 Answers
Play sound on collision 1 Answer
Tiny tag changing and checking problem 2 Answers
Most efficient way to handle projectile collisions? 2 Answers
Destroy object on touch of object with specific class 3 Answers