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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Prevent Rigidbody2D automatically push player and enemy when they're on same position.

Discussion in '2D' started by unity_TADI_tSWHbzBpw, Apr 24, 2022.

  1. unity_TADI_tSWHbzBpw

    unity_TADI_tSWHbzBpw

    Joined:
    Sep 9, 2019
    Posts:
    2
    Hello! I'm making a 2D platformer and both my player and enemies are using dynamic Rigidbody2D's.

    So far this works fine: My player gets hit by the enemy --> player is slightly pushed back and hurt --> player get invincible for a few milliseconds, and while invincible, the player is able to walk through any enemy.

    Now here is the problem: When my player is invincible it's walking through the enemies fine, but if I'm right on the position where the enemy is standing and my invincibility frames disappear, the enemy gets pushed away (the physics in the enemies RigidBody2D is pushing it away from the players RigidBody2D) and this is obviously a wrong behaviour.

    Is there a way to fix this? For example if I can do a check right before the invincibility frames are gone, and see if the player is inside the enemy collision, then cause another push and apply damage and invincibility frames on the player? How can I manually check that collision between player and enemy in code without using the OnCollision2D? Note: I can't use the OnCollision2D since during my invincibility frames, the collision between player and enemy is being fully ignored!

    Thank you!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,965
    Interesting problem.

    It might be necessary to have an invisible proxy GameObject / Collider that:

    - tries to track the player position, but...
    - stays outside of all colliders all the time, but...
    - also ignores colliding with the player (layer collision matrix)

    This way it will remain outside and you can use it as the proxy place to restore the player to.
     
    unity_TADI_tSWHbzBpw likes this.
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,623
    The same way you'd do any check, use a physics query.

    Just use something such as Rigidbody2D.OverlapCollider.
     
    unity_TADI_tSWHbzBpw likes this.
  4. unity_TADI_tSWHbzBpw

    unity_TADI_tSWHbzBpw

    Joined:
    Sep 9, 2019
    Posts:
    2
    Thank you both for the suggestions!

    Rigidbody2D.OverlapCollider fixed the issue for me! Just before ending the damage immunity, I check with Rigidbody2D.OverlapCollider if we're colliding with an enemy, and if we are, I apply another knockback to our player and this works really well.
     
    MelvMay and Kurt-Dekker like this.