Skip to content

Instantly share code, notes, and snippets.

@Wolfos
Last active May 19, 2020 03:15
Show Gist options
  • Save Wolfos/aafada4728c5fa328eff8455f62e58ee to your computer and use it in GitHub Desktop.
Save Wolfos/aafada4728c5fa328eff8455f62e58ee to your computer and use it in GitHub Desktop.
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;
}
}
@chanon
Copy link

chanon commented Oct 22, 2018

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.)

	private static CircleCollider2D _distanceCollider;

	// get distance from collider to point
	public static float DistanceFrom(this Collider2D collider, Vector2 point) {
		if (_distanceCollider == null) {
			GameObject go = new GameObject("DistanceCollider");
			Object.DontDestroyOnLoad(go);
			_distanceCollider = go.AddComponent<CircleCollider2D>();
			_distanceCollider.radius = 0f;
		}

		_distanceCollider.enabled = false;
		_distanceCollider.transform.position = point;
		_distanceCollider.enabled = true;
		ColliderDistance2D dist = collider.Distance(_distanceCollider);
		return dist.distance;
	}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment