1. 程式人生 > >unity程式碼建立草和模擬風的效果

unity程式碼建立草和模擬風的效果

    void Start()
    {
        Test4();
    }

    //草
    private Vector3[] grassArray = new Vector3[7];
    private GameObject grassobj;
    void Test4()
    {
        GameObject obj = new GameObject();
        obj.name = "grass";
        grassobj = obj;
        MeshFilter meshFilter = obj.AddComponent<MeshFilter>();
        //mesh的頂點,按照圖的我們順時針寫就行
        Vector3[] newVertices =
        {
            new Vector3(0, 0, 0), new Vector3(0 ,1 ,0) , new Vector3(0, 2, 0), new Vector3(0, 3, 0), 
            new Vector3(0.3f, 2 ,0 ), new Vector3(0.6f, 1 , 0), new Vector3(0.9f, 0 ,0)
        };
        grassArray = newVertices;
        //uV座標,照抄上面的,去除z
        Vector2[] newUV =
        {
            new Vector2(0, 0), new Vector2(0, 1), new Vector2(0, 2), new Vector2(0, 3), 
            new Vector2(0.3f, 2), new Vector2(0.6f, 1), new Vector2(0.9f,0)
        };
        int[] newTriangles =
        {
            2,3,4,1,2,4,1,4,5,0,1,5,0,5,6,//順時針渲染正面
            2,4,3,1,4,2,1,5,4,0,5,1,0,6,5//逆時針渲染背面
        };
        Mesh mesh = new Mesh();
        meshFilter.mesh = mesh;
        //頂點 三角面 uv
        mesh.vertices = grassArray;
        mesh.uv = newUV;
        mesh.triangles = newTriangles;
        //渲染
        MeshRenderer renderer = obj.AddComponent<MeshRenderer>();
        Material mat = new Material (Shader.Find("Standard"));
        mat.color = Color.green;
        renderer.material = mat;
    }

    public float wind;
    Vector3[] baseVertices =
    {
        new Vector3(0, 0, 0), new Vector3(0 ,1 ,0) , new Vector3(0, 2, 0), new Vector3(0, 3, 0), 
        new Vector3(0.3f, 2 ,0 ), new Vector3(0.6f, 1 , 0), new Vector3(0.9f, 0 ,0)
    };
    // Update is called once per frame
    void Update()
    {
        //模擬草被風影響
        //頂點高度越高的草越容易被影響
        wind = Mathf.Sin(Time.time);//sin波
        for (int i = 0; i < grassArray.Length; i++)
        {
            if (grassArray[i].y == 3)
            {
                //高度為3的草
                grassArray[i].x = baseVertices[i].x + (wind * baseVertices[i].y * 0.2f);
            }
            else if (grassArray[i].y == 2)
            {
                //高度為2的草
                grassArray[i].x = baseVertices[i].x + (wind * baseVertices[i].y * 0.15f);
            }
            else if (grassArray[i].y == 1)
            {
                //高度為1的草
                grassArray[i].x = baseVertices[i].x + (wind * baseVertices[i].y * 0.1f);
            }
        }

        grassobj.GetComponent<MeshFilter>().mesh.vertices = grassArray;
    }

  

通過程式碼建立的草的mesh

y軸單位是1

0到6的距離是0.9

 

一棵草左右搖擺

寫法比較粗糙,後面再研究下更好的寫法