Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[SOLVED] How do I check if player is still inside boss' collider?

Discussion in 'Scripting' started by PlazmaInteractive, Sep 13, 2016.

  1. PlazmaInteractive

    PlazmaInteractive

    Joined:
    Aug 8, 2016
    Posts:
    114
    I've got a boss enemy set up and the way it works is that if the player hits it, the player loses some health and the boss loses some health too. But, there is a glitch that after the player got hit by the boss once and stays inside the boss, the player basically can't lose health because OnTriggerEnter2D only calls once. I know I can use OnTriggerStay2D but the boss loses health too quickly as the method is called once per frame. How do I ensure that if the player is still within boss' collider, it will lose health?

    Extra info: I've set up my player a short invincibility ability if it hits any enemy.

    Boss OnTriggerEnter2D script:
    Code (csharp):
    1. void OnTriggerEnter2D(Collider2D other)
    2. {
    3.     if (other.gameObject.tag == "Player" && other.GetComponent<PlayerController>().invincible == false)
    4.     {
    5.         stats.CurHealth -= stats.playerCollisionDmg;
    6.     }
    7. }
    Player's OnTriggerEnter2D script:
    Code (csharp):
    1. IEnumerator OnTriggerEnter2D(Collider2D other)
    2. {
    3.     if(other.GetComponent<EnemyStatsController>() != null)
    4.     {
    5.         if (!invincible)
    6.         {
    7.             stats.CurHealth -= other.GetComponent<EnemyStatsController>().collisionDamage;
    8.             yield return new WaitForSeconds(0.01f);
    9.             invincible = true;
    10.             GetComponent<Animator>().enabled = true;
    11.             yield return new WaitForSeconds(5f);
    12.             invincible = false;
    13.             GetComponent<Animator>().enabled = false;
    14.             GetComponent<SpriteRenderer>().enabled = true;
    15.         }
    16.     }
    17. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    OnTriggerStay with a simple time check sounds like the simplest approach

    Code (csharp):
    1.  
    2. //pseudo
    3. OnTriggerEnter()
    4. {
    5. impactTime = Time.time
    6. }
    7.  
    8. OnTriggerStay()
    9. {
    10. if(Time.time > impactTime + damageDelay)
    11. {
    12. DoDamage()
    13. impactTime = Time.time
    14. }
    15. }
    16.  
     
  3. PlazmaInteractive

    PlazmaInteractive

    Joined:
    Aug 8, 2016
    Posts:
    114
    This solution worked, thanks!