Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Math Question for procedural generation of a plane

Discussion in 'Scripting' started by SCMcArthur, Apr 24, 2014.

  1. SCMcArthur

    SCMcArthur

    Joined:
    Feb 24, 2014
    Posts:
    5
    So I have a script set up to generate a 16X16 grid of vertices. I want to loop through them and set up the triangles between the vertices to make it into a solid mesh plane. I am having trouble wrapping my head around the numbers I need to use for the triangles, I keep ending up with really weird results. What sort of equation would I use so that I can loop through and set up the triangle array?
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Assuming widthResolution and lengthResolution are the number of verts:
    if you WANT a 2x2 grid of quads, that means 3x3 verts, with 2x2x6 tri indices.
    This also assumes that your verts are indexed like
    6 7 8
    3 4 5
    0 1 2
    Code (csharp):
    1.  
    2. int[] tris = new int[( widthResolution - 1 ) * ( lengthResolution - 1 ) * 6];
    3. for ( int y = 0; y < lengthResolution - 1; y++ ) {
    4.             for ( int x = 0; x < widthResolution - 1; x++ ) {
    5.                 tris[( ( y * ( widthResolution - 1 ) ) + x ) * 6 + 0] = y * widthResolution + x;
    6.                 tris[( ( y * ( widthResolution - 1 ) ) + x ) * 6 + 1] = ( y + 1 ) * widthResolution + x;
    7.                 tris[( ( y * ( widthResolution - 1 ) ) + x ) * 6 + 2] = y * widthResolution + x + 1;
    8.  
    9.                 tris[( ( y * ( widthResolution - 1 ) ) + x ) * 6 + 3] = y * widthResolution + x + 1;
    10.                 tris[( ( y * ( widthResolution - 1 ) ) + x ) * 6 + 4] = ( y + 1 ) * widthResolution + x;
    11.                 tris[( ( y * ( widthResolution - 1 ) ) + x ) * 6 + 5] = ( y + 1 ) * widthResolution + x + 1;
    12.  
    13.             }
    14.  
    15.         }
     
  3. SCMcArthur

    SCMcArthur

    Joined:
    Feb 24, 2014
    Posts:
    5
    Thank you, that helped a lot!