Hi everyone.
I’d like to know if there is any way to find the shortest distance between a point and a Collider2d (of any shape)? Or, as alternative, a point on Collider2d closest to a given point.
It seems there is no easy way to do that without some custom hardcore math. Which is probably not the case, because the solution must be fast as it’s going to be called in real-time every frame.
Funny (actually no) thing is that Box2d provides a useful b2Distance function which calculates the shortest distance between two shapes (or Collider2ds in Unity’s terminology). But for some reason Unity does not expose such a useful utility.
Yes, it was indeed added in 5.6.0b7. It’s now at a very late beta 5.6.0b11 and won’t be long for final release.
There are probably approximations you can do, certainly you can perform Collider2D.Cast to check where it would contact but that won’t necessarily give you closest point, just first contact in a specific direction. There are probably other approximations you could do using overlapCircle but it’ll only ever be that beyond implementing your own distance function.
@MelvMay : I’m using Unity 5.5f. Are the functions “Collider2d.bounds.ClosestPoint()” and “Collider2d.bounds.SqrDistance()” not meant to address the shortest distance problem between a point and collider 2d ? They seem to work for the most part…but I was hoping to get your comments first before mentioning the issues with these functions
Bounds are just an AABB, they do not give you closest point to the collider edges unless you’re talking about a non-rotated BoxCollider2D. Not good for circles, capsules, polygons, edges etc.
I believe you can use Physics2D.Distance / Collider2D.Distance / Rigidbody2D.Distance to get the closest point. These methods return ColliderDistance2D which has pointA and pointB variables. Exactly what you need.
Are we sure about that? How would we know what it does internally? I too need the Collider2D.ClosestPoint method for something I’m doing right now, but it doesn’t appear to be in yet…
Was the equivalent of a Collider2D.ClosestPoint ever added? I don’t believe Physics2D/Collider2D.Distance will work for me since I specifically need to check between a point and a collider, not between two colliders.