Terrain

2023-12-13 20:27:30

最近工作中遇到一个需求,需要在地形上随机生成对应的植被,需要对地形就行解析。

1.对地形的贴图的解析

需要把对应坐标在Terrain Layer成分获取到

2.计算出对应坐标中Terrain Layer占比最大的成分当作当前坐标的主要成分,例如草地,湿地

 Vector3 terrainLocalPos = new Vector3(x,0,z) - TestTerrain.transform.position;
                    float texCoordX = terrainLocalPos.x / terrainData.size.x;
                    float texCoordZ = terrainLocalPos.z / terrainData.size.z;
                    var textureData = terrainData.GetAlphamaps(
                    (int)(texCoordX * terrainData.alphamapWidth),
                    (int)(texCoordZ * terrainData.alphamapHeight),
                    1, 1
                    );
                    float max = 0.0f;
                    int maxid = -1;
                    for (int i = 0; i < terrainData.alphamapLayers; i++)
                    {
                        if (textureData[0, 0, i] > max)
                        {
                            max = textureData[0, 0, i];
                            maxid = i;//成分占比最高的Layer
                        }
                        //maters[x, z, i] = textureData[0, 0, i];
                           
                    }
                    flags[x, z] = maxid+1;

3.在对应的高度生成对应的植被

 for (int z = 0; z < zz; z++)
            {
                for (int x = 0; x < xx; x++)
                {
                    if (flags[x, z] != 0)
                    {
                        GameObject go = Instantiate(gameObjects[flags[x, z]]);
                        //获取当前地形的高度,使生成的物体和地形贴合
                        float yyy= Terrain.activeTerrain.SampleHeight(new Vector3(x, 0, z));
                        go.transform.position = new Vector3(x, yyy, z);
                    }
                }
            }

文章来源:https://blog.csdn.net/MikeJackSTG/article/details/134979290
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。