一、首先导入高度图到项目中并对其进行如下设置,点击Apply:
二、新建地形Terrain,进行如下操作:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
using UnityEditor;
//[CanEditMultipleObjects]
public class CustomTerrain : MonoBehaviour {
public Texture2D heightMapImage;
public Vector3 heightMapScale = new Vector3(1, 1, 1);
//获取地形(物体)对象
public Terrain terrain;
//TerrainData里有地形所有的数据
public TerrainData terrainData;
//每次编辑完脚本内容返回编辑器时运行后会执行此方法
private void OnEnable()
{
//初始化地形数据 先获取地形再获取本身的地形数据
terrain = gameObject.GetComponent<Terrain>();
terrainData = Terrain.activeTerrain.terrainData;
Debug.LogError(terrain);
}
//在现有地形上添加高度图
public void LoadTexture()
{
float[,] heightMap;
//此处的高度图与地形大小尺寸一样
heightMap = new float[terrainData.heightmapWidth, terrainData.heightmapHeight];
for (int x = 0; x < terrainData.heightmapWidth; x++)
{
for (int z = 0; z < terrainData.heightmapHeight; z++)
{
//图片是二维矩阵,heightMapImage.GetPixel((int)(x * heightMapScale.x),(int)(z * heightMapScale.z))表示给地形的每个位置赋予对应的像素
//像素值这是一个介于0和1之间的值
//x,z之所以乘以缩放比例是因为我们能够以不同方式在整个表面上拉伸图像数据,最后将所有颜色转为灰度
//最后将其乘以高度比例就可以实际将这些值提高,使其从表面冒出来
heightMap[x, z] = heightMapImage.GetPixel((int)(x * heightMapScale.x), (int)(z * heightMapScale.z)).grayscale * heightMapScale.y;
}
}
terrainData.SetHeights(0, 0, heightMap);//最后将这些数据用用于地形
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using EditorGUITable;
[CustomEditor(typeof(CustomTerrain))]
[CanEditMultipleObjects]
public class CustomTerrainEditor : Editor {
SerializedProperty heightMapScale;
SerializedProperty heightMapImage;
//是否折叠编辑面板
bool showLoadHeights = false;
private void OnEnable()
{
//找到需要反复更改的属性
heightMapScale = serializedObject.FindProperty("heightMapScale");
heightMapImage = serializedObject.FindProperty("heightMapImage");
}
//绘制编辑面板
public override void OnInspectorGUI()
{
//更新所有序列化的值
serializedObject.Update();
//获取自定义的地形属性脚本组件
CustomTerrain terrain = (CustomTerrain)target;
#region
// //添加高度图图像编辑面板
showLoadHeights = EditorGUILayout.Foldout(showLoadHeights, "Load Heights");
if (showLoadHeights)
{
EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
GUILayout.Label("Load Heights From Texture", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(heightMapImage);
EditorGUILayout.PropertyField(heightMapScale);
if (GUILayout.Button("Load Texture"))
{
terrain.LoadTexture();
}
}
#endregion
//应用发生的所有更改
serializedObject.ApplyModifiedProperties();
}
}
高度图拖放之后点击运行,点击Load Texture按钮
下面改变scale大小后点击运行,点击Load Texture按钮
补充:进入这个网站https://terrain.party/可进行地理位置高度图的选择和下载