Unity3D 动态改变地形

时间:2023-03-09 17:13:19
Unity3D 动态改变地形

直接获取TerrainData进行修改即可

using System.Collections;
using UnityEngine;
using UnityEditor; public class DynamicCreateTerrain : MonoBehaviour
{
public TerrainData terrainData;
private float[,] heightsBackups; void Start()
{
//var terrain = CreateTerrain();
ModifyTerrainDataHeight(terrainData);
// 5秒后恢复地形
StartCoroutine(Disable());
} // 动态创建地形
public Terrain CreateTerrain()
{
TerrainData terrainData = new TerrainData();
terrainData.heightmapResolution = ;
terrainData.baseMapResolution = ;
terrainData.size = new Vector3(, , );
terrainData.alphamapResolution = ;
terrainData.SetDetailResolution(, );
GameObject obj = Terrain.CreateTerrainGameObject(terrainData);
AssetDatabase.CreateAsset(terrainData, "Assets/Terrain_ModifyHeight.asset");
AssetDatabase.SaveAssets();
return obj.GetComponent<Terrain>();
} // 动态改变地形
public void ModifyTerrainDataHeight(TerrainData terrainData)
{
int width = terrainData.heightmapWidth;
int height = terrainData.heightmapHeight;
float[,] array = new float[width, height];
print("width:" + width + " height:" + height);
for (int i = ; i < width; i++)
for (int j = ; j < height; j++)
{
float f1 = i;
float f2 = width;
float f3 = j;
float f4 = height;
float baseV = (f1 / f2 + f3 / f4) / * ;
array[i, j] = baseV * baseV;
}
// 备份高度图
heightsBackups = terrainData.GetHeights(, , width, height);
// 设置高度图
terrainData.SetHeights(, , array);
} IEnumerator Disable()
{
yield return new WaitForSeconds();
Debug.Log("Recove Terrain.");
terrainData.SetHeights(, , heightsBackups);
}
}

需要注意的是,如果是在Editor模式下, 这样操作会直接修改TerrainData的数据,需要注意备份,不过打包完就没事,不会再被修改了。

这种做法可以动态改变地形,用来实现一些例如挖洞等的效果。

动态改变地形的插件:

https://www.assetstore.unity3d.com/cn/#!/content/65795

Unity3D 动态改变地形