Skip to content

Instantly share code, notes, and snippets.

@Gillissie
Created May 3, 2011 03:59
Show Gist options
  • Save Gillissie/952795 to your computer and use it in GitHub Desktop.
Save Gillissie/952795 to your computer and use it in GitHub Desktop.
static function createPlane(tileWidth:int,tileDepth:int,spacing:int):Mesh
{
var mesh:Mesh = new Mesh();
var vertices:Vector3[] = new Vector3[(tileWidth + 1) * (tileDepth + 1)];
var triangles:int[] = new int[tileWidth * tileDepth * 2 * 3];
var uvs:Vector2[] = new Vector2[(tileWidth + 1) * (tileDepth + 1)];
var i:int = 0;
var x:int = 0;
var z:int = 0;
var uvOffset:float = 1.0 / (Mathf.Max(tileWidth,tileDepth) + 1);
// Create vertices.
for (z = 0; z < tileDepth + 1; z++)
{
for (x = 0; x < tileWidth + 1; x++)
{
vertices[i] = Vector3(x * spacing,0,z * spacing);
uvs[i] = Vector2(uvOffset * x, uvOffset * z);
i++;
}
}
i = 0;
// Create triangles.
for (z = 0; z < tileDepth; z++)
{
for (x = 0; x < tileWidth; x++)
{
// Create two triangles at a time (a quad), so increment by 6 with each tile.
// Figure out which indexes are for the four vertices around the current tile's quad.
var idx1:int = z * (tileWidth + 1) + x;
var idx2:int = (z + 1) * (tileWidth + 1) + x;
var idx3:int = (z + 1) * (tileWidth + 1) + x + 1;
var idx4:int = z * (tileWidth + 1) + x + 1;
triangles[i] = idx1;
triangles[i + 1] = idx2;
triangles[i + 2] = idx3;
triangles[i + 3] = idx1;
triangles[i + 4] = idx3;
triangles[i + 5] = idx4;
i += 6;
}
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.Optimize();
mesh.RecalculateBounds();
mesh.RecalculateNormals();
Debug.Log("bounds size: " + mesh.bounds.size);
return mesh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment