Search Unity

Procedural Geometry - Tris

Discussion in 'Scripting' started by kittik, Nov 12, 2018.

  1. kittik

    kittik

    Joined:
    Mar 6, 2015
    Posts:
    483
    I am making a system, where shapes can be made at runtime, and adopt vertices and triangles to create a procedural shape. These shapes are defined by the users mouse movement.

    I am not understanding if there is a foolproof way to create the tris, so that they can create the tris in the places, even when shapes are different i.e. if a shape is a kite, triangle, or something more abstract.

    I know that the triangle array should contain a length divisible by 3, but cannot see a one size fits all solution to the problem. Any help would be appriciated.

    Code (CSharp):
    1.     void CreateShape()
    2.     {
    3.         GameObject go = new GameObject();
    4.         go.AddComponent<MeshFilter>();
    5.         go.AddComponent<MeshRenderer>();
    6.         go.transform.localScale *= 2.5f;
    7.  
    8.         Mesh mesh = new Mesh();
    9.  
    10.         Vector3[] vertices = new Vector3[selectedNodes.Count];
    11.         int[] tris = new int[selectedNodes.Count];
    12.  
    13.         for(int i = 0; i < vertices.Length; i++)
    14.         {
    15.             vertices[i] = new Vector3(selectedNodes[i].xPos, selectedNodes[i].yPos, 0f);
    16.             tris[i] = i;
    17.         }
    18.  
    19.         mesh.vertices = vertices;
    20.         mesh.triangles = tris;
    21.  
    22.         go.GetComponent<MeshFilter>().mesh = mesh;
    23.     }
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,119
    A square is 2 tris (your tri list will have six indices), a pentagon is 3 tris (9 indixes), etc

    This is called 'Triangulation' and there are dozens of resources available on performing it
     
  3. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    843