Last active
May 19, 2020 03:15
-
-
Save Wolfos/aafada4728c5fa328eff8455f62e58ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public static class Collider2DExtension | |
{ | |
/// <summary> | |
/// Return the closest point on a Collider2D relative to point | |
/// </summary> | |
public static Vector2 ClosestPoint(this Collider2D col, Vector2 point) | |
{ | |
GameObject go = new GameObject("tempCollider"); | |
go.transform.position = point; | |
CircleCollider2D c = go.AddComponent<CircleCollider2D>(); | |
c.radius = 0.1f; | |
ColliderDistance2D dist = col.Distance(c); | |
Object.Destroy(go); | |
return dist.pointA; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!
I have tried modifying this to not destroy the game object and keep it for future calls. However, it then doesn't work correctly .. it seems like it is using the old position.
EDIT: OK, got it to work. Needed to do an enable/disable toggle. Notice that radius 0 also works.
(This version returns the distance as that is what I needed.)
Not sure which is better performance-wise, as I read enabling/disabling collider is also costly.
EDIT2: From the forum post, looks like Unity 2019.1 will finally have this added.