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

Push player with object

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

  1. IbrahimAlkaber

    IbrahimAlkaber

    Joined:
    Dec 9, 2019
    Posts:
    53
    Hi,
    i'm working on script that can object push players when it hits them, what should I use to do like this?
    Thanks
     
  2. Sherlock-jr

    Sherlock-jr

    Joined:
    Oct 2, 2014
    Posts:
    11
    You can use rigidbodys on players and on the object and let the physics engine of unity to take care the rest or you coud use a collider on the object and add a script that implements OnColiisionEnter event, and inside that event put some code that applies force to the player that its colliding with the object.
     
    IbrahimAlkaber and faqeerhasnain like this.
  3. faqeerhasnain

    faqeerhasnain

    Joined:
    Nov 5, 2018
    Posts:
    74
    Yeah as @Sherlock-jr mentioned,adding rigidbodies is the right choice
     
    IbrahimAlkaber likes this.
  4. IbrahimAlkaber

    IbrahimAlkaber

    Joined:
    Dec 9, 2019
    Posts:
    53
    Code (CSharp):
    1.     void OnCollisionEnter(Collision c)
    2.     {
    3.         float force = 3;
    4.         if (c.gameObject.tag == "Player")
    5.         {
    6.             Vector3 dir = c.contacts[0].point - transform.position;
    7.             dir = -dir.normalized;
    8.             GetComponent<Rigidbody>().AddForce(dir * force);
    9.             Debug.Log("Forced");
    10.  
    11.         }
    12.     }
    Doesn't work
     
  5. IbrahimAlkaber

    IbrahimAlkaber

    Joined:
    Dec 9, 2019
    Posts:
    53
    Solved , Thank you guys