【发布时间】:2026-02-24 00:45:01
【问题描述】:
我正在尝试从图像/纹理颜色(从像素)设置地形的高度图,我做了这个简单的例子:
using UnityEngine;
public class TerrainExample : MonoBehaviour
{
public Texture2D map, grassTexture;
public float amp = 8;
public Color waterColor = new Color(0.427f, 0.588f, 0.737f); //new Color32(127, 168, 200, 255); //0.427, 0.588, 0.737
private Vector3 mapPlane = new Vector3(4200, 0, 3000);
public void Start()
{
GameObject TerrainObj = new GameObject("TerrainObj");
TerrainData _TerrainData = new TerrainData();
Debug.Log(new Vector3(mapPlane.x, 600, mapPlane.z));
_TerrainData.size = new Vector3(mapPlane.x / (1.6f * amp), 600, mapPlane.z / (1.6f * amp));
_TerrainData.heightmapResolution = 4096;
_TerrainData.baseMapResolution = 1024;
_TerrainData.SetDetailResolution(1024, 16);
//Set terrain data
int _heightmapWidth = _TerrainData.heightmapWidth,
_heightmapHeight = _TerrainData.heightmapHeight;
float[,] heights = new float[_heightmapWidth, _heightmapHeight];
float stepX = (float)map.width / _heightmapWidth, stepY = (float)map.height / _heightmapHeight;
int w = 0;
for (float i = 0; i < map.width; i += stepX)
for (float k = 0; k < map.height; k += stepY)
{
int ii = (int)i, kk = (int)k, i2 = (int)(i / stepX), k2 = (int)(k / stepY);
heights[i2, k2] = map.GetPixel(ii, kk) == waterColor ? .25f : .5f;
}
_TerrainData.SetHeights(0, 0, heights);
//Set terrain grass texture
SplatPrototype terrainTexture = new SplatPrototype();
terrainTexture.texture = grassTexture;
SplatPrototype[] splatPrototype = new SplatPrototype[1] { terrainTexture };
_TerrainData.splatPrototypes = splatPrototype;
TerrainCollider _TerrainCollider = TerrainObj.AddComponent<TerrainCollider>();
Terrain _Terrain2 = TerrainObj.AddComponent<Terrain>();
_TerrainCollider.terrainData = _TerrainData;
_Terrain2.terrainData = _TerrainData;
TerrainObj.transform.position = -mapPlane * 10 / 2 + Vector3.up * 100;
}
}
我的地图纹理如下:
原始地图有 7000x5000 像素,我的高度图有 4096 个单位。因此,我必须通过计算每次迭代的步长来进行一点翻译(如您在 第 25 行 中所见)
我做的很简单,当有水时我只放一个高度的 0.25f (600/4 = 150),当有不同于水的东西时我只放一个高度的 0.5f (600 / 2 = 300)。 (第 31 行)
但由于某种原因,我只能在地形上看到这条奇怪的线条:
我错过了什么???
这是Unitypackage。
【问题讨论】:
标签: c# unity3d texture2d terrain heightmap