0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Unityのスクリプトで頂点計算してポリゴンを描く

Posted at

はじめに

Unity上で、数式をベースに3Dオブジェクトを作っていくためのサンプル。
ただの四角形1つではなく、256x256のメッシュを作る。
法線計算は頂点座標から自動でやってくれるので助かる。

基本的には、頂点バッファ&インデックスバッファをセットして描画なので、頂点の変更がないなら、高速。

頂点を毎フレーム更新するような使い方の場合は、書き換えの時間と、法線の再計算が発生するので、少し遅くなる。

環境

Unity 2021.3.17

手順

Create Emptyで空のオブジェクトを作る
Add ComponentからMesh Filterを追加する。
Add ComponentからMesh Rendererを追加する。
以下の新規スクリプトを作成し、追加する

DrawQuad.cs
using UnityEngine;

public class DrawQuad : MonoBehaviour
{
    Mesh mesh;
    Vector3[] v3s = new Vector3[256*256];//グリッドのサイズ
    int[] tri = new int[255*255*2 *3];//ポリゴン数*3頂点

    void Start()
    {
        mesh = new Mesh();

        //頂点座標計算
        for (int z = 0; z < 256; z ++)
        {
            for (int x = 0; x < 256; x ++)
            {
                float y; //適当な波で高さ
                y = Mathf.Sin(x * 0.1f);
                y *= Mathf.Sin(z * 0.2f);
                y *= 10;
                // 頂点座標
                v3s[z*256+x].Set(x, y, z);
            }
        }
        mesh.SetVertices(v3s);//頂点座標セット

        //インデックス計算
        for (int z = 0; z < 255; z++)
        {
            for (int x = 0; x < 255; x++)
            {
                // 三角形2個で一つの四角ポリゴン
                // 1つ目の三角形
                tri[(z * 255 + x) * 6 + 0] = z * 256 + x;
                tri[(z * 255 + x) * 6 + 1] = z * 256 + x + 256;
                tri[(z * 255 + x) * 6 + 2] = z * 256 + x + 1;
                // 2つ目の三角形
                tri[(z * 255 + x) * 6 + 3] = z * 256 + x + 1;
                tri[(z * 255 + x) * 6 + 4] = z * 256 + x + 256;
                tri[(z * 255 + x) * 6 + 5] = z * 256 + x + 257;
            }
        }
        mesh.SetTriangles(tri, 0);//インデックスセット

        // 法線の計算
        mesh.RecalculateNormals();

        // 表示
        MeshFilter meshFilter = GetComponent<MeshFilter>();
        meshFilter.mesh = mesh;

        MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
        meshRenderer.material = new Material(Shader.Find("Standard"));
        meshRenderer.material.color = Color.gray;
    }
}

image.png

カメラ位置は、適宜、移動回転してください。

参考

グリッドのポリゴンメッシュの頂点番号をどのように計算式で表せばよいか、図説で参考になるはず。
床井先生のサイト
http://web.wakayama-u.ac.jp/~tokoi/unity_mesh.pdf

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?