Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

How to make players push each other

Discussion in 'Scripting' started by Karen_M_2005, Sep 11, 2019.

  1. Karen_M_2005

    Karen_M_2005

    Joined:
    Sep 27, 2018
    Posts:
    11
    Hello I am making a 2D Game and I'm stuck on the 2 player collisions. When I move both players toward each other they just stop moving when they collide. Basically they push with the same force and their rigidbody force cancels out. What can I do to kind of make their forces uneven so they can push each other when moving towards each other without just stopping.

    Thanks!

    Code (CSharp):
    1.     private void OnCollisionStay2D(Collision2D collision)
    2.     {
    3.         if (collision.gameObject.GetComponent<Rigidbody2D>() != null)
    4.         {
    5.             rbOther = collision.gameObject.GetComponent<Rigidbody2D>();
    6.  
    7.             if (collision.gameObject != this.gameObject)
    8.             {
    9.                 rb.AddForce(rb.velocity + rbOther.velocity * externalForceImpactDownscaler);
    10.             }//
    11.         }
    12.         else return;
    13.     }
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,265
    have you tried changing character rigidbody mass ? I think this might help
     
  3. Karen_M_2005

    Karen_M_2005

    Joined:
    Sep 27, 2018
    Posts:
    11
    I don't want to mess with the mass because their jumping mechanic would get mixed up. Because they would have different masses and so they would jump different distances.

    Thanks Anyway!
     
    Last edited: Sep 11, 2019
  4. Karen_M_2005

    Karen_M_2005

    Joined:
    Sep 27, 2018
    Posts:
    11
    I just want to decrease velocity of the second object that collided to make the first object that collided push the second one.
     
  5. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    814
    I can see 2 ways to do this. Look into Physics materials for 2D physics in unity, specifically the bounce property. If that works to your liking, great. If not, well its gonna be through scripting, which I'm hoping to avoid for your sake for the time being.
     
  6. Karen_M_2005

    Karen_M_2005

    Joined:
    Sep 27, 2018
    Posts:
    11
    Thanks!

    I would reply as soon as I try it out.
     
  7. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    753
    You could set mass for collisions, then push your little guys in a way that ignores mass.

    Changing velocity directly ignore mass. Ex: myRigidbody.velocity+=Vector3.up; add 1 up, no matter what mass. Then only 2 of the 4 of the AddForce commands divide by mass, the other half ignore mass. I think, ForceMode.VelocityChange adds the velocity with no changes to it. They're made for situations exactly like this.