Hello!
I try to implement damage and knockback event with cooldown. It happens when character touches enemy or stands beside it.
bool invulnerable = false;
public float horizontalKnockbackForce;
public float horizontalKnockbackForce;
float knockbackDuration = 2f;
public IEnumerator KnockbackAndHurt(Transform obj)
{
invulnerable = true;
Hurt(hp); // function for health point substraction
float timer = 0;
while (knockbackDuration > timer)
{
timer += Time.deltaTime;
rb.AddForce(Vector2.up * verticalKnockbackForce);
if (transform.position.x < obj.position.x)
{
rb.AddForce(Vector2.right * horizontalKnockbackForce);
}
else
{
rb.AddForce(Vector2.left * horizontalKnockbackForce);
}
}
yield return 0;
invulnerable = false;
}
It works fine with OnCollisionEnter2D:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.gameObject.CompareTag("Enemy"))
{
if (invulnerable == false)
{
StartCoroutine(KnockbackAndHurt(collision.collider.transform));
}
}
}
But OnCollisionStay2D is invoking coroutine too fast or several times simultaneously, so character is getting much damage and flying away too far:
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.collider.gameObject.CompareTag("Enemy"))
{
if (invulnerable == false)
{
StartCoroutine(KnockbackAndHurt(collision.collider.transform));
}
}
}
How can I make it work and combine it with OnCollisionEnter2D?