外接円1.0の正多角形メッシュを作る
「あー、メッシュ欲しいなー、けどメタセコやMaya立ち上げて面張るのダルいなー」っていう時に使える関数。
この間の連休で作ったので共有。
public static Mesh GenerateRegularPolygonMeshXY(int vertexCount) { //Meshの作成 Mesh mesh = new Mesh(); Vector2[] points = new Vector2[vertexCount]; float div = 360f / (float)vertexCount; for (int i = 0; i < vertexCount; ++i) { float rad = div * (float)i * Mathf.Deg2Rad; points[i] = new Vector2(Mathf.Sin(rad), Mathf.Cos(rad)); } //頂点 var verticies = new Vector3[points.Length + 1]; verticies[0] = Vector3.zero;//中心 for (int i = 0, length= points.Length; i < length; ++i) { verticies[i+1] = new Vector3(points[i].x, points[i].y, 0f); } mesh.vertices = verticies; //色 Color[] colors = new Color[points.Length + 1]; colors[0] = Color.black;//中心 for (int i = 1, length = colors.Length; i < length; ++i) { colors[i] = Color.white; } mesh.colors = colors; //面 var indicies = new int[vertexCount * 3]; for (int i = 0; i < vertexCount; ++i) { indicies[i * 3 + 0] = 0; indicies[i * 3 + 1] = i + 1; indicies[i * 3 + 2] = ((i + 2 >= verticies.Length) ? 1 : i + 2); } mesh.triangles = indicies; return mesh; }
これで、外接円を1.0としたXY平面上の正多角形Meshを作成できます。
※外接円の半径が1.0なので、4角形を作った場合、1辺の長さが1.0になるわけではないのでご注意!
一応ですが、頂点カラーで中心黒~外周白で色付けもしています。
「pointsいらねぇじゃん」と思うかもしれないけど、
このpointsをPolygonCollider2Dのpointsに入れるとそのままぴったりサイズのコライダが出来るので
良い感じにカスタマイズして下さいな。
※記事頭のスクショは自前でシェーダを書いたものなので、上記の模様がそのまま表示はされないです。