• Unity3D 动态改变地形 Unity3D Dynamic Change Terrain


    直接获取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 = 513;
            terrainData.baseMapResolution = 513;
            terrainData.size = new Vector3(50, 50, 50);
            terrainData.alphamapResolution = 512;
            terrainData.SetDetailResolution(32, 8);
            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 + " height:" + height);
            for (int i = 0; i < width; i++)
                for (int j = 0; j < height; j++)
                {
                    float f1 = i;
                    float f2 = width;
                    float f3 = j;
                    float f4 = height;
                    float baseV = (f1 / f2 + f3 / f4) / 2 * 1;
                    array[i, j] = baseV * baseV;
                }
            // 备份高度图
            heightsBackups = terrainData.GetHeights(0, 0, width, height);
            // 设置高度图
            terrainData.SetHeights(0, 0, array);
        }
    
        IEnumerator Disable()
        {
            yield return new WaitForSeconds(5);
            Debug.Log("Recove Terrain.");
            terrainData.SetHeights(0, 0, heightsBackups);
        }
    }

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

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

    动态改变地形的插件:https://www.assetstore.unity3d.com/cn/#!/content/65795 
    terrain

    Ref: https://www.cnblogs.com/jeason1997/p/5776594.html

  • 相关阅读:
    log日志框架和LocationAwareLogger问题
    Eclipse 各种小图标的含义
    自定义log4j日志级别
    在Tomcat配置JNDI数据源的三种方式
    mybatis中"#"和"$"的区别
    Postman用法简介-Http请求模拟工具
    mustache模板技术(转)
    VS的编译选项
    Java Service Wrapper简介与使用
    还活着
  • 原文地址:https://www.cnblogs.com/open-coder/p/12331404.html
Copyright © 2020-2023  润新知