Search Unity

Procedural Polygon Collider 2D

Discussion in '2D' started by CasualDutchman, Dec 12, 2018.

  1. CasualDutchman

    CasualDutchman

    Joined:
    Jan 20, 2016
    Posts:
    37
    I am working a procedural terrain system, which can be destroyed and build.
    The problem I am having now, is that the collider does not match the terrain.



    The way I am getting points, is by checking if a pixel as 1 or 2 neighbor pixels. Only then the pixel's location will be used as a point for the collider.

    Then I sort the List of Vector2 locations in a clockwise way.

    This sorting works when the points are in a certain way.

    Code (CSharp):
    1. //from: https://pastebin.com/1RkaP28U
    2. //from: https://answers.unity.com/questions/877169/vector2-array-sort-clockwise.html
    3. public class ClockwiseComparer : IComparer<Vector2> {
    4.     private Vector2 m_Origin;
    5.  
    6.     public ClockwiseComparer(Vector2 origin) {
    7.         m_Origin = origin;
    8.     }
    9.  
    10.     public int Compare(Vector2 first, Vector2 second) {
    11.         return IsClockwise(first, second, m_Origin);
    12.     }
    13.  
    14.     public static int IsClockwise(Vector2 first, Vector2 second, Vector2 origin) {
    15.         if (first == second)
    16.             return 0;
    17.  
    18.         Vector2 firstOffset = first - origin;
    19.         Vector2 secondOffset = second - origin;
    20.  
    21.         float angle1 = Mathf.Atan2(firstOffset.x, firstOffset.y);
    22.         float angle2 = Mathf.Atan2(secondOffset.x, secondOffset.y);
    23.  
    24.         if (angle1 < angle2)
    25.             return -1;
    26.  
    27.         if (angle1 > angle2)
    28.             return 1;
    29.  
    30.         return (firstOffset.sqrMagnitude < secondOffset.sqrMagnitude) ? -1 : 1;
    31.     }
    32. }
    Can someone help me with this, or maybe suggest a different method of doing this.
     
  2. CasualDutchman

    CasualDutchman

    Joined:
    Jan 20, 2016
    Posts:
    37
    All these red points will become part of the collider.



    And because terrain can be destroyed, this might also happen

     
  3. Thimble2600

    Thimble2600

    Joined:
    Nov 27, 2015
    Posts:
    165