Skip to content

Instantly share code, notes, and snippets.

@ruccho
Created March 26, 2018 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruccho/82e3b5bdff991034eb853aec0a8eab9f to your computer and use it in GitHub Desktop.
Save ruccho/82e3b5bdff991034eb853aec0a8eab9f to your computer and use it in GitHub Desktop.
A helper for CompositeCollider2D (using PolygonCollider2D) to create circle polygon
//CompositeCollider2D can use only BoxCollider2D and PolygonCollider2D.
//This script helps your projects to use circle for CompositeCollider2D through creating circle polygon and setting it to PolygonCollider2D.
//Attach this to the GameObject, insert radius and number of points and click "Create Circle Polygon".
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[RequireComponent(typeof(PolygonCollider2D))]
public class PolygonCollider2DHelper : MonoBehaviour
{
private PolygonCollider2D PolygonCollider2DRef;
void Start(){}
void Update(){}
public void SetCirclePolygon(float radius, int resolution)
{
PolygonCollider2DRef = GetComponent<PolygonCollider2D>();
Vector2[] points = new Vector2[resolution];
for(int i = 0; i < resolution; i++)
{
Vector2 v = new Vector2(0, radius);
Quaternion q = Quaternion.AngleAxis((360f / resolution) * i, Vector3.forward);
points[i] = q * v;
}
PolygonCollider2DRef.points = points;
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(PolygonCollider2DHelper))]
public class EditorPolygonCollider2DHelper : Editor
{
[SerializeField]
float radius;
[SerializeField]
int resolution;
public override void OnInspectorGUI()
{
radius = EditorGUILayout.FloatField("Radius:", radius);
resolution = EditorGUILayout.IntField("Number of points:", resolution);
if (GUILayout.Button("Create Circle Polygon"))
{
((PolygonCollider2DHelper)target).SetCirclePolygon(radius, resolution);
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment