Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Is there an easy way to know if a rigidbody is colliding with an object?

Discussion in 'Physics' started by HypothicEntropy, Mar 18, 2018.

  1. HypothicEntropy

    HypothicEntropy

    Joined:
    Mar 24, 2014
    Posts:
    26
    This seems like it should be pretty simple but as far as I know, there is no way to know whether an object is colliding with another object or not unless you keep track of and manage every collision which is difficult. Is there an easy way to poll the rigidbody and see whether it is currently colliding or not, or must I keep track of and manage every collision using OnCollisionEnter/Exit?
     
  2. HypothicEntropy

    HypothicEntropy

    Joined:
    Mar 24, 2014
    Posts:
    26
    Ahh, I think I figured it out, I think I need code like this:

    Code (CSharp):
    1. public virtual void OnCollisionStay(Collision c)
    2.         {
    3.             m_CollisionOccurred = true;
    4.         }
    5.  
    6.         public virtual void FixedUpdate()
    7.         {
    8.             m_CollisionOccurred = false;
    9.         }
    Because FixuedUpdate happens before OnCollisionStay, this works. Sad this isn't already implemented by default.
     
    MarkusGod likes this.
  3. BoogieD

    BoogieD

    Joined:
    Jun 8, 2016
    Posts:
    236
    You can get access to the other collider in OnCollisionEnter(Collision collision).
    'collision.contacts' is an array of ContactPoints where you can get 'otherCollider' and 'point' etc.
    There may be several ContactPoints so best to check them all.
    https://docs.unity3d.com/ScriptReference/ContactPoint.html

    Perhaps you need:
    collision.collider.attachedRigidbody
     
  4. StickyHoneybuns

    StickyHoneybuns

    Joined:
    Jan 16, 2018
    Posts:
    207

    There is nothing more that needs to be implemented. You should read the docs first.

    https://docs.unity3d.com/ScriptReference/GameObject-tag.html

    If you want to look for a specific collision it is really simple. Like this:
    Code (CSharp):
    1. void OnCollisionEnter(Collision collision)
    2. {
    3. if(collision.gameObject.tag== "myObject")//you can also have a specific name as well
    4. {
    5. do something
    6. }
    7. }
     
  5. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    It's more efficent to use:
    Code (CSharp):
    1.  
    2. if(collision.gameObject.CompareTag("myObject"))
    3.  
     
    StickyHoneybuns likes this.
  6. StickyHoneybuns

    StickyHoneybuns

    Joined:
    Jan 16, 2018
    Posts:
    207