- Home /
Drawing A 2D Capsule (Same of CapsuleCollider2D)
Hello,
I was trying to create system which will be available only on runtime. A capsule collider will be added in runtime aswel. For visualizing capsule collider 2d before runtime, I need to draw it with a custom gizmo in simple way. (The size and offset values will be given to custom gizmo and in runtime, the real capsule collider 2d will obtain those offset and size values.) Any ideas about this ?
Thank you.
Answer by rostok · Feb 06, 2021 at 10:34 PM
It's a little late but never too late for necroposting. You can fiddle with this code. It should support different directions and rotation however it will not fit perfectly capsules with strange proportions (ie. horizontal size.x=1 size.y=4)
CapsuleCollider2D cc = GetComponent<CapsuleCollider2D>();
if (!cc) return;
Gizmos.color = Color.yellow;
float step = 0.2f;
float r = Mathf.Min(cc.size.x, cc.size.y)/2;
float d = Mathf.Max(cc.size.x, cc.size.y)/2-r;
Vector3 lp = Vector3.positiveInfinity;
for (float a=-Mathf.PI; a<=Mathf.PI+step; a+=step) {
float x = Mathf.Cos(a);
float y = Mathf.Sin(a);
Vector3 np = new Vector3(x, y) * r;
np += (cc.direction == CapsuleDirection2D.Vertical ? Vector3.up : Vector3.zero) * d * Mathf.Sign(y);
np += (cc.direction == CapsuleDirection2D.Horizontal ? Vector3.right : Vector3.zero) * d * Mathf.Sign(x);
np = transform.TransformPoint(np);
if (lp!=Vector3.positiveInfinity) Gizmos.DrawLine(lp, np);
lp = np;
}
the code above only draws 2d capsule. what is a collider offset?
I achieved the behavior with this simple code before @rostok posted an answer. You may use this as well. https://github.com/JMetalian/DrawCollider Additionally, thank you @rostok
Answer by nomadic · Oct 09, 2019 at 08:02 PM
You could do a rough version using two spheres (Gizmos.DrawWireSphere)
For a more elegant version you could essentially recreate the capsule collider gizmo by utilizing UnityEditor.Handles (Handles.DrawLine, Handles.DrawWireDisc, Handles.DrawWireArc)