void OnValidate()
 {
     if (coll == null)
     {
         //When first getting a reference to the collider save the paths
         //so that the optimization is redoable (by performing it on the original path
         //every time)
         coll = GetComponent <PolygonCollider2D>();
         for (int i = 0; i < coll.pathCount; i++)
         {
             List <Vector2> path = new List <Vector2>(coll.GetPath(i));
             originalPaths.Add(path);
         }
     }
     //Reset the original paths
     if (tolerance <= 0)
     {
         for (int i = 0; i < originalPaths.Count; i++)
         {
             List <Vector2> path = originalPaths[i];
             coll.SetPath(i, path.ToArray());
         }
         return;
     }
     for (int i = 0; i < originalPaths.Count; i++)
     {
         List <Vector2> path = originalPaths[i];
         path = ShapeOptimizationHelper.DouglasPeuckerReduction(path, tolerance);
         coll.SetPath(i, path.ToArray());
     }
 }
예제 #2
0
        void OnValidate()
        {
            coll    = coll ?? GetComponent <EdgeCollider2D>();
            polygon = polygon ?? GetComponent <PolygonCollider2D>();

            List <Vector2> path       = new List <Vector2>();
            Vector2        upperRight = polygon.bounds.max;
            Vector2        upperLeft  = polygon.bounds.min;

            upperLeft.y = upperRight.y;
            for (int i = 0; i < rayBudget; i++)
            {
                float t = (float)i / (float)rayBudget;
                //interpolate along the upper edge of the collider bounds
                Vector2        rayOrigin = Vector2.Lerp(upperLeft, upperRight, t);
                RaycastHit2D[] hits      = Physics2D.RaycastAll(rayOrigin, edgeNormalOpposite, polygon.bounds.size.y);

                for (int j = 0; j < hits.Length; j++)
                {
                    RaycastHit2D hit = hits[j];
                    if (hit.collider == polygon)
                    {
                        Vector2 localHitPoint = transform.InverseTransformPoint(hit.point);
                        path.Add(localHitPoint);
                        break;
                    }
                }
            }
            if (tolerance > 0)
            {
                path = ShapeOptimizationHelper.DouglasPeuckerReduction(path, tolerance);
            }
            coll.points = path.ToArray();
        }