How to get the closest vertex of the Polygon Collider 2D in code?


Title pretty much explains the entire question. 3D colliders have a function called ClosestPointOnBounds, but that is for the bounding box and not the collider mesh itself(?).

Alternatively, how do I access the vertices that make up a collider in code? col.poly.paths nor col.ColliderInfo.Vertices works.

You use the points array of the PolygonCollider2D. These points are in local space, so you will have to convert them to world space before doing the comparison (or you could convert the world to local and do the comparison in local space). Here is a bit of code to demonstrate. Attach it do a game object with a PolygonCollider2D. Create a marker object (I created a sphere of size (.1,.1,.1), and drag and drop it on the ‘Display’ variable in the Inspector. Run the app and click in the Game window. The display object will be moved to the closes vertex on the collider.

Note I wrote it for both an Orthographic and Perspective camera. The code could be simplified a bit if it was only going to be used on an Orthographic camera.

#pragma strict

public var display : Transform;
private var poly : PolygonCollider2D;

function Start () {
	poly = GetComponent(PolygonCollider2D);

function Update () {
	if (Input.GetMouseButtonDown(0)) {
		var pos = Input.mousePosition;
		pos.z = transform.position.z - Camera.main.transform.position.z;
		pos = Camera.main.ScreenToWorldPoint(pos);
		var placement : Vector3 = FindClosest(poly, pos);
		placement.z = transform.position.z;
		display.position = placement;

function FindClosest(poly : PolygonCollider2D, point : Vector2) : Vector2 {
	var dist = Mathf.Infinity;
	var result =;
	for (var corner : Vector2 in poly.points) {
		var test = transform.TransformPoint(corner);
		var d = Vector2.Distance(test, point);
		if (d < dist) {
			dist = d;
			result = test;
	return result;