Search Unity

Question Prevent impact Force of projectile on player without influence player input [Rigidbody]

Discussion in 'Physics' started by Silasbla, May 9, 2023.

  1. Silasbla

    Silasbla

    Joined:
    Oct 7, 2020
    Posts:
    6
    Hey community,

    I have two Rigidboy2Ds with one 2DCollider for each object.
    GameObejct1 is my player which is controlled by the Player Input System (movement per rigidbody forces).
    GameObject2 is a projectile (spear) thrown by the player. Physics also simulated by rigidbodys and the unity physic engine.

    Now I'm trying to implement an invincible status for the player which prevent the player from dying (Destroying gameobject). Normaly the collision of a spear and a player leads to destroy and respawning the player.

    But if the invincible status of a player is true. I dont want to destroy the player nether I want to have physical impact by hitting the player with the spear.

    I've already created a "OnCollisionEnter2D" function in the Monobehavior of the spear which detects the collision with an invincible player. But I cant figure out how I can prevent the decoy of the player which is hitted by the spear. I had the idea of setting the mass of the spear to 0 if the collision with an invincible player is detected. Also tried to add the oppositve force of the hitting spear to the player...for example:

    Code (CSharp):
    1.     private void OnCollisionEnter2D(Collision2D collision)
    2.     {
    3.         var targetCollider = collision.collider.gameObject;
    4.         var targetLayer = LayerMask.LayerToName(targetCollider.layer);
    5.  
    6.         if (targetLayer.Contains("Player"))
    7.         {
    8.  
    9.             if (targetCollider.transform.parent.GetComponentInChildren<PlayerControlScript>().isInvincible)
    10.             {
    11.                 Vector2 reversePower;
    12.                 reversePower = collision.relativeVelocity * -1;
    13.                 Debug.Log(collision.relativeVelocity);
    14.                 collision.rigidbody.AddForce(reversePower, ForceMode2D.Force);
    15.                 Debug.Log(reversePower);
    16.             }
    17.         }
    18.  
    19.  
    20.         Destroy(this.gameObject);
    21.     }
    I can't set the Rigidbody of the player to kinematic while the player is invicble because the player should furthermore be controlled by the users input.

    Is there a possibility to detect the collision and negate the physical input to the player without losing control of the users input to the rigidbody?


    Player Configuration:
    upload_2023-5-9_10-52-45.png

    Spear Configuration:
    upload_2023-5-9_10-53-53.png