ポリゴンを出力するチュートリアルをちょっとだけ改造したメモ。[tutorial](http://catlikecoding.com/unity/tutorials/procedural-grid/)
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] | |
public class CubeTest : MonoBehaviour { | |
public int xSize, ySize; | |
void Awake(){ | |
StartCoroutine( this.Generate() ); | |
} | |
Vector3[] vertices; | |
IEnumerator Generate(){ | |
var wait = new WaitForSeconds(0.05f); | |
Mesh mesh; | |
GetComponent<MeshFilter>().mesh = mesh = new Mesh(); | |
mesh.name = "Procedural Grid"; | |
// 頂点情報 | |
this.vertices = new Vector3[ (this.xSize + 1 ) * ( this.ySize + 1 )]; | |
// UV情報 | |
Vector2[] uv = new Vector2[vertices.Length]; | |
Vector4[] tangents = new Vector4[vertices.Length]; | |
Vector4 tangent = new Vector4(1f, 0f, 0f, -1f); // [Thus w should always be 1 or -1.](http://docs.unity3d.com/ja/current/ScriptReference/Mesh-tangents.html) | |
for (int i = 0, y = 0; y <= this.ySize; y++) { | |
for (int x = 0; x <= this.xSize; x++, i++) { | |
this.vertices[i] = new Vector3(x, y); // モデル座標空間における値 | |
//uv[i] = new Vector2(x / xSize, y / ySize); | |
uv[i] = new Vector2((float)x / xSize, (float)y / ySize); | |
//yield return wait; | |
tangents[i] = tangent; | |
} | |
} | |
// 頂点を入れる | |
mesh.vertices = vertices; | |
// uv情報を入れる | |
mesh.uv = uv; | |
mesh.tangents = tangents; | |
int[] triangles = new int[ xSize * ySize * 6 ]; | |
for( int y = 0,count = 0, total = 0; y < this.ySize; y ++, total ++ ){ | |
for(int x = 0; x < this.xSize; x++, count += 6, total ++ ){ | |
this.DrawTriCorrectLocation (ref triangles, count, total); | |
mesh.triangles = triangles; // 代入すると描画される | |
yield return wait; | |
this.DrawTriInversion (ref triangles, count, total); | |
mesh.triangles = triangles; | |
yield return wait; | |
Debug.Log("Draw" + x + ":" + y); | |
} | |
} | |
mesh.RecalculateNormals(); | |
} | |
void DrawTriCorrectLocation(ref int[] triangles, int count, int total ){ | |
triangles[ count + 0] = total; | |
triangles[ count + 1] = total + xSize + 1; | |
triangles[ count + 2] = total + 1; | |
} | |
void DrawTriInversion( ref int[] triangles, int count, int total ){ | |
triangles[ count + 3 ] = total + 1; | |
triangles[ count + 4 ] = total + xSize + 1; | |
triangles[ count + 5 ] = total + xSize + 2; | |
} | |
void OnDrawGizmos(){ | |
if( this.vertices == null ) return; | |
Gizmos.color = Color.black; | |
for( int i = 0; i < this.vertices.Length; i++ ){ | |
Gizmos.DrawSphere( this.vertices[i] + this.transform.position, 0.1f ); // モデル座標空間における位置に自身の位置を合算させる。 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment