Search code examples
c#unity-game-enginecollision-detectiongame-physics

Unity Sphere Collision


I know Unity has a lot of ways of working out whether or not an object is inside another object, whether or not they are touching etc., but what I'm wanting to know is something a bit more specific.

In my research I found out about Physics.OverlappedSphere and from what I can read this gives you information about every object with a collider within the sphere. What I would like to know is if I had two spheres which made use of Physics.OverlappedSphere, could I find out at which point(s) these spheres meet and intersect?

If this isn't possible, can someone suggest another way I may be able to find out this information?


Solution

  • If you use the Collision class and therein the Collision.contacts (which is an array of contactpoints) you should be able to...

    Taken from here

    function OnCollisionStay(collision : Collision) {
        for (var contact : ContactPoint in collision.contacts) {
            print(contact.thisCollider.name + " hit " + contact.otherCollider.name);
            // Visualize the contact point
            Debug.DrawRay(contact.point, contact.normal, Color.white);
        }
    }
    

    Try getting the size of the contacts array and look at the last points.

    // Print how many points are colliding this transform 
    // And print the first point that is colliding.
    function OnCollisionEnter(other : Collision) {
        print("Points colliding: " + other.contacts.Length);
        print("First point that collided: " + other.contacts[0].point);
    }