- Home /
2D - Player damaged when attacking enemies
I have a Player Object with a child Sword Object. The Player has "Player" as tag, the Sword "Weapon". I also have enemies, bearing the tag "Enemy".
Whenever an Enemy hits the Players Body, the Player HP drops. Whenever the Sword hits an Enemy, the Enemy HP drops. However, whenever an Enemy touches the Sword the Player HP drops as well! Here is my code:
PlayerDamage.cs
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Player" && other.gameObject.tag != "Weapon")
{
other.gameObject.GetComponent<PlayerHealthController>().Damage(damage);
}
}
EnemyDamage.cs
void OnCollisionEnter2D(Collision2D other)
{
if ((other.gameObject.tag == "Enemy" || other.gameObject.name == "Enemy"))
{
other.gameObject.GetComponent<EnemyHealthController>().Damage(damage);
}
}
Is it because the Sword is a child of the Player?
Answer by BluezamX · Jun 26, 2018 at 05:20 PM
Made a new Empty Object, attached both the original Player and the Sword to it. This fixed the issue.
Answer by Harinezumi · Jun 26, 2018 at 02:10 PM
In short, yes.
A bit longer answer, when an object has a Collider
on a child, scripts are notified for collision with any and all of the child Colliders
.
So either separate the sword from the player and move it differently, or before damaging the player check if the enemy was just hit by the sword. Unfortunately, I don't know of a better solution.
EDIT: actually, it may be possible to solve it with a common root for the player and the sword which doesn't have a collider or script on it, but is moved with/by the player. Then the player damage script is only on the player child object, while the sword damage script only on the sword child object. I haven't tested this, but I think this way collisions with the sword will not notify scripts on the player, because they aren't in child-parent relationship.
I tried yours, but it interfered with Animations I already had made. However, by creating a new Empty Object and attaching both the Player and the Sword to it as Children, I managed to work around the issue.
Your answer
Follow this Question
Related Questions
Help with 2D Hit Detection! 0 Answers
Collision on specific Frames 1 Answer
Why does my OnCollisionEnter2D not work? 3 Answers
Unity2D Collision is bugged 0 Answers