码迷,mamicode.com
首页 > 编程语言 > 详细

Unity3D 动态改变地形

时间:2016-08-16 16:13:57      阅读:1633      评论:0      收藏:0      [点我收藏+]

标签:

直接获取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:" + 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);
    }
}

需要注意的是,这样会直接修改TerrainData的高度图数据,直接将硬盘上的数据也改了,如果只是游戏效果需要,在改变时需要备份,结束游戏后还原数据。

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

 

动态改变地形的插件:

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

技术分享

 

Unity3D 动态改变地形

标签:

原文地址:http://www.cnblogs.com/jeason1997/p/5776594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!