Hello. From what I gathered, Physics2D.Distance is meant to handle such use cases.
However, Physics2D.Distance seems to return the closest point to any polygon edge (including the ones that are generated inside the shape when editing the polygon shape). Thus it’s not a sufficient approach to get an available position outside the entire polygon shape.
What would be an appropriate way to get the desired result?
You might try to use an edge collider instead of the polygon collider, if that’s possible for you, as that has no internal lines.
Alternatively, you could just loop through all the lines in the polygon and check the minimum distance from the line to each of the four points of your box. You can find the closest point on line algorithm easily enough by googling.
Well it’s designed to show you the spatial relationship between two colliders and essentially would give you the data that physics would use to move out of overlap.
With a PolygonCollider2D the “outline” is simply an authoring thing and isn’t what physics uses. It’s convenient rather than adding all those shapes manually. The physics engine (Box2D) doesn’t understand concave outlines as physics objects. It only knows Circles, Capsules, Edges and Polygon (8 vertex and convex). A PolygonCollider2D will produce N polygon primitives to fill the region you specify. Look at the inspector on any Collider2D and it’ll give you the shape-count; this is also available in the API along with retrieving all the physics shapes.
As above, you can author using an EdgeCollider2D or add a CompositeCollider2D, set the PolygonCollider2D to use it and set the output as “Outlines” (Edges). Know though that Edges don’t have any interior to collide with as they’re “open” shapes, only the edges themselves will intersect with other shapes.
Thanks for the follow-up! Both solutions are helpful.
Just wanted to clarify regarding this part -
essentially would give you the data that physics would use to move out of overlap.
After using ColliderDistance2D .normal * .distance to get an offset, in some cases it seems to still have an overlap. Is it expected? Do physics perform this operation multiple times until there is no overlap?
(Attaching an example of said overlap - after applying the offset)