shapes2d icon indicating copy to clipboard operation
shapes2d copied to clipboard

Option to fit-inside-rect when creating a shape from a PolygonCollider2D

Open all-iver opened this issue 5 years ago • 0 comments

This would help in cases where you have a PolygonCollider2D with points that don't fit inside a 1x1 rect. Some example code below that would do this for a poly shape (not done for paths)...replace the appropriate parts of ShapeEditor.FromPolygonCollider2D(). However, this means the shape doesn't fit to the collider - the fix would be to then click "Set Polygon Collider 2D" to re-create the collider inside the shape's bounds. If we do this, we'd want to make it optional somehow.

            PolygonCollider2D pc2d = shape.GetComponent<PolygonCollider2D>();
            if (shape.settings.shapeType == ShapeType.Polygon) {
                if (pc2d.points.Length >= 64) {
                    EditorUtility.DisplayDialog("Too many points", 
                            "The PolygonCollider2D has too many points (max 64).", "Okay");
                    return;
                }
                // get the polygon collider's bounds
                var bounds = new Rect(pc2d.points[0].x, pc2d.points[0].y, 0, 0);
                for (int i = 0; i < pc2d.points.Length; i++) {
                    var p = pc2d.points[i];
                    bounds.xMin = Mathf.Min(bounds.xMin, p.x);
                    bounds.xMax = Mathf.Max(bounds.xMax, p.x);
                    bounds.yMin = Mathf.Min(bounds.yMin, p.y);
                    bounds.yMax = Mathf.Max(bounds.yMax, p.y);
                }
                var scale = 1 / Mathf.Max(bounds.width, bounds.height);
                // transform to shape space, re-centering and scaling so that the major dimension fits just inside
                Vector3[] points = new Vector3[pc2d.points.Length];
                for (int i = 0; i < pc2d.points.Length; i++) {
                    var p = (pc2d.points[i] - bounds.center) * scale;
                    points[i] = shape.transform.TransformPoint(p);
                }
                Undo.RecordObject(shape, "Edit Shapes2D Polygon Vertices");
                shape.SetPolygonWorldVertices(points);
                EditorUtility.SetDirty(target);
            } else if (shape.settings.shapeType == ShapeType.Path) {

all-iver avatar Jul 29 '20 16:07 all-iver