Home > OS >  Taking damage in unity 2D
Taking damage in unity 2D

Time:08-10

I am making a script where the player triggers with the enemy and takes the damage from him.

public class PlayersHealth : MonoBehaviour
{
    public int currentHealth;
    public int maxHealth;
    private bool inCollider = false;

    void Start()
    {
        currentHealth = maxHealth;
    }

    void OnTriggerEnter2D(Collider2D collision){
     if(inCollider == false){
     if(collision.CompareTag("Enemy")){
        inCollider = true;
     }
     }
    }

    void OnTriggerExit2D(Collider2D collision){
        if(inCollider == true){
        if(collision.CompareTag("Enemy")){
           currentHealth--;
           inCollider = false;
           }
        }
    }
}

The main problem is that I am taking to much damage because of this going in/out of the trigger collider.

I have tried to fix that by making bool "inCollider" that should solve the problem. Unfortunately, problem still remains.

I am a newbie to Unity and C#, so I would be glad to see alternative ways to do a script like this.

Maybe I should do this in enemy attack script?

CodePudding user response:

I'm assuming you're making some kind of platformer or sidescroller here. Typically, games will give you a set amount of seconds after taking damage where you're invincible. In most Super Mario games, for example, after taking damage Mario flashes and is invincible for 158 frames, or 2.528 seconds.

Other common solutions to this problem include knocking the player away from the enemy on collision, or killing the enemy that caused the player to take damage.

CodePudding user response:

You can damage player with time interval, while the interval requirement isn't met the requirement, you can think player is invincible.

private float _lastHitTime;
private float _hitInterval;

void OnTriggerStay2D(Collider2D other)
{
    if (Time.fixedUnscaledTime - _lastHitTime >= _hitInterval)
    {
        if (other.TryGetComponent<EnemyComponent>())
        {
            __lastHitTime = Time.fixedUnscaledTime;
            //do player stuff here
        }
    }
}
  • Related