Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

OnCollisionStay Issue

Discussion in 'Scripting' started by arturnik17, May 28, 2020.

  1. arturnik17

    arturnik17

    Joined:
    Dec 13, 2017
    Posts:
    19
    OnCollisionStay is called every fixed frame (0.02 in my game).
    I have an enemy that follows a player and sticks to him, so first touch is OnCollisionEnter and afterwards OnCollisionStay is calling OnCollisionEnter in it.
    Issue is when multiple enemies are touching the player at the same time OnCollisionStay gets called in every enemy at the exact same frame, so my player is losing more health than it should.

    I have a flag that checks if the player is getting hit but that does not help since all of the OnCollisionStay happen to be called simultaneously. Am I missing something?

    Code (CSharp):
    1.     public virtual void OnCollisionEnter(Collision collision) {
    2.         if (collision.transform.tag == "Collider") {
    3.             if (collision.transform.name == "Player") {
    4.                 // Damage Player
    5.                 if (EnemyManager.playerHit) return; // playerHit is set to true in ReceiveDamage()
    6.                 pController.ReceiveDamage(damage);
    7.                 ChangeDirectionOnHit(collision.GetContact(0).normal.x, collision.GetContact(0).normal.y);
    8.             }
    9.             else {
    10.                 ChangeDirectionOnHitToPlayer();
    11.             }
    12.         }
    13.     }
    OnCollisionStay just calls for OnCollisionEnter.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    If two enemies are touching your player, I assume it is dealing 2x damage. What exactly did you expect? Is it actually dealing more than that? Did you print out the actual damage being dealt to verify it numerically?

    If you expect two (or more) enemies touching the player to only deal 1x damage, then usually you have a proxy counter that counts these touches, and when a frame has a nonzero number of things touching, you take constant damage and reset that counter for the next frame.
     
    arturnik17 likes this.