hello everyone
please i have code when enemy want hit player
public virtual void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == “Sword”)
{
StartCoroutine(TakeDamage());
}
}
public override IEnumerator TakeDamage()
{
Health--;
if (Die)
{
MyAnim.SetBool("Die", Die);
}
yield return null;
}
but when enemy hit player
health Decreases 3 time because player have 3 collider2d
EDIT: The first solution has too many error possibilities, so i came up with a new one, which is a lot easier to implement as well. Check the bottom of the text.
Since colliders will call OnTriggerEnter2D one by one, maybe this solution can help. But it will only work, if the enemy’s sword is not too fast, otherwise it could fail.
You should create a new boolean variable in the Player script. This variable should be false by default. When the sword collides with one of the colliders, it checks if it has decreased the health yet, or not. If it has, it will not decrease it again, until the sword exits the colliders.
But we have to create an integer variable too, because we need to know, how many colliders has the sword met. We can only reset the boolean variable to false (and thereby allow the sword to damage again) if the sword has exited all the colliders.
(Note that this solution only works if the sword leaves all the colliders before striking again.)
int enteredColliders = 0;
bool hasDecreased = false;
public virtual void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Sword")
{
enteredColliders++;
if(!hasDecreased)
{
StartCoroutine(TakeDamage());
hasDecreased = true;
}
}
}
public virtual void OnTriggerExit2D(Collider2D other)
{
enteredColliders--;
if(enteredColliders == 0)
{
hasDecreased = false;
}
}
EDIT: Instead of having 3 colliders to maintain the shape of the character, you should have a polygon collider. It automatically follows the shape of the sprite, but you can override it if you wish. Having only one collider attached to the gameobject will simply get rid of the problem without implementing new codes.