Finding the points where game objects contact a sphere

I’m currently working on a feature for a project which requires a script that returns with a high degree of accuracy the points in the game world where “physical” (more or less anything with a mesh) game objects are in contact or overlapping with a sphere of space of an arbitrary radius.

The fact that this script requires the points of contact rather than the game objects within a volume of space is the part me and my colleague are having trouble with; running overlap sphere worked fine for getting the colliders in a particular area, but as far as I can tell, that particular function isn’t able to return contact points.

The current solution we’ve come up with involves spawning a rotating sphere collider and quickly expanding it and returning the contact points of the resulting collisions, though I suspect that approach will have a number of problems we haven’t encountered yet.

Does anyone know of a better approach to this problem?

What we’re using for this now is as follows, though I feel it’s going to have some problems we haven’t run into yet.

var collisionPoints = new Array();

function Start () {
 
}

function Update () {
 transform.localScale += new Vector3(0.1, 0.1, 0.1);
 transform.Rotate(Time.deltaTime, 0, 0);
}
 
 function OnCollisionEnter(collision : Collision) {
  for (var contact : ContactPoint in collision.contacts) {
   collisionPoints.Add(contact.point);
   Debug.DrawRay(contact.point, contact.normal, Color.white);
   Physics.IgnoreCollision(collider, collision.collider, true);
  }
  print(collisionPoints);
 }

If you have a list of colliders within the sphere (which you say you already do) then all you need to do is …

Subtract the position of the target object with the position of the center “finder” sphere - this will give you a Vector3 with a magnitude according to distance and a direction.

Then, check the magnitude and see if it’s greater than (Sphere radius - target collider radius) and if so, that object resides on the edge and not inside further.

Then, if you need the same spot exactly on the edge of the “finder” sphere, just normalize that Vector3 you found earlier, then multiply the radius of the “finder” sphere against the result and you’ll have the exact offset to get a point on the circumference of the sphere.

Don’t make it harder than it needs to be, use Physics.SphereCast!

http://docs.unity3d.com/Documentation/ScriptReference/ContactPoint.html

http://docs.unity3d.com/Documentation/ScriptReference/Collision-contacts.html

Can’t really help with performance, but the links should answer the question. Though, I suspect you already know about them?

RayCastHit will also give you the info you want but using that version of the function requires more power. RayCastHit Array is returned from RayCastAll type functions (as mentioned in my comment above).

Make sure to use LayerMasks!!!

SphereCastAll link