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’re making changes to the Unity Runtime Fee pricing policy that we announced on September 12th. Access our latest thread for more information!
    Dismiss Notice
  3. Dismiss Notice

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

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

  1. Silasbla


    Oct 7, 2020
    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);
    6.         if (targetLayer.Contains("Player"))
    7.         {
    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.         }
    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:

    Spear Configuration: