Skip to content

Instantly share code, notes, and snippets.

@allfake
Forked from adekbadek/showedgecollider.cs
Last active December 30, 2023 19:02
Show Gist options
  • Save allfake/e899878b14cadf1e09d5 to your computer and use it in GitHub Desktop.
Save allfake/e899878b14cadf1e09d5 to your computer and use it in GitHub Desktop.
Show 2D Polygon Collider as Gizmo, also in Edit Mode (Not support rotation)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class VisibleCollider : MonoBehaviour {
public bool showLine = true;
public Color lineColor = Color.blue;
private PolygonCollider2D[] thisColliders;
private List<Vector2[]> pointsList;
private List<Vector3> _tList;
void OnDrawGizmos() {
if (!showLine) {
return;
}
pointsList = new List<Vector2[]>();
_tList = new List<Vector3>();
thisColliders = gameObject.GetComponents<PolygonCollider2D>();
foreach (PolygonCollider2D c in thisColliders) {
Vector2[] pointWithOffset = new Vector2[c.points.Length];
for (int i = 0; i < c.points.Length; i++) {
pointWithOffset[i] = c.points[i] + c.offset;
}
pointsList.Add(pointWithOffset);
_tList.Add(c.transform.position);
}
for (int j = 0; j < pointsList.Count; j++) {
Vector2[] points = pointsList[j];
Vector3 _t = _tList[j];
Gizmos.color = lineColor;
for (int i = 0; i < points.Length - 1; i++) {
Gizmos.DrawLine (new Vector3 (points [i].x + _t.x, points [i].y + _t.y), new Vector3 (points [i + 1].x + _t.x, points [i + 1].y + _t.y));
}
Gizmos.DrawLine(new Vector3 (points [points.Length - 1].x + _t.x, points[points.Length - 1].y + _t.y), new Vector3 (points [0].x + _t.x, points [0].y + _t.y));
}
}
}
@nekropants
Copy link

You can account for scale and rotation by
Gizmos.matrix = transform.localToWorldMatrix;

and removing
private List _tList;

so that the position offset isn't applied twice

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