Get point on surface of Collider2D from inside collider.

Hey there,

I’m trying to do some 2D Verlet Integration physics. It’s mostly working, but one hurdle that’s popped up is trying to merge it with existing physics objects. The effect I’m going for is to treat Unity’s colliders as static geometry that my Verlet objects are not allowed to intersect. The trouble is, to do this I need to construct a constraint for how to resolve the case where a Verlet node IS inside a collider, and how to move it out. The simplest and most effective result would be “move the node to the nearest point on the surface of the Collider”. Sounds simple enough, and at first glance it seems like Collider2D.ClosestPoint would do the job.

However, with ClosestPoint, if the point specified is already inside the collider, that point is just returned without being changed. This of course is completely useless for this use case.

I’ve tried a few methods to resolve this, such as using an iterator to find a point near to the surface, but outside the collider, and finding the closest point to that, but it’s somewhat unstable. I’ve also tried constructing my own function to find this point, but this is quite slow, and complicated to build.

I’m wondering if there’s any sensible way to achieve this. Does anyone have any ideas? Thanks!

I think that if you use Collider.Raycast backward (not Physics.Raycast) so that the ray passes through both the center of mass and your point from the outside of the collider, you might get an approximation of your nearest point. However I believe the math for the nearest point depends on the collider type, and can only be generalized through some algorythm slowly approaching the target value.

Of course it would be better to avoid such problem by using raycasts to prevent a collision from happened in the first place.