如何将 SetAlphamaps 设置为一个特定的纹理?

how to set the SetAlphamaps to one certain texture?

我想用某种纹理改变我的地形纹理。我对设置 splatmapdata 感到困惑,任何人都可以帮助我吗??

private void ChangeTexture(Vector3 WorldPos)
{
    print ("changeTexture");

    int mapX = (int)(((WorldPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
    int mapZ = (int)(((WorldPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);


    float[,,] splatmapData = terrainData.GetAlphamaps(3, 3, 15, 15);
    terrainData.SetAlphamaps (mapX, mapZ, splatmapData);
    terrain.Flush ();
}

GetAlphamaps

返回的数据

The returned array is three-dimensional - the first two dimensions represent x and y coordinates on the map, while the third denotes the splatmap texture to which the alphamap is applied.

或者简单地说 a float[x, y, l] where

  • x = 像素宽度
  • y = 像素高度
  • l = 纹理层

所以假设你想在这个像素坐标处将它设置为某个纹理你所做的是

  • 将纹理图层的权重设置为 1
  • 将所有其他图层权重设置为 0

所以假设你有,例如3 层,您希望第二层(= 索引 1)成为全加权纹理:

float[,,] splatmapData = terrainData.GetAlphamaps(mapX, mapZ, 15, 15);

// Iterate over x-y coordinates within the array
for(var y = 0; i < 15; y++)
{
    for(var x = 0; x < 15; x++)
    {
        // Set first layers weight to 0
        splatmapData[x, y, 0] = 0;

        // Set second layer's weight to 1
        splatmapData[x, y, 1] = 1;

        // Set third layer's weight to 0
        splatmapData[x, y, 2] = 0;
    }
}

terrainData.SetAlphamaps(mapX, mapZ, splatmapData);

然后我会为图层实现一个 enum,比如

public enum TerrainLayer
{
    Default = 0,
 
    Green,
    Red
}

所以您可以简单地将相应的层索引作为参数传递 - 比传递 int 值本身更安全:

private void ChangeTexture(Vector3 worldPos, TerrainLayer toLayer)
{
    print ("changeTexture");

    int mapX = (int)(((worldPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
    int mapZ = (int)(((worldPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);

    float[,,] splatmapData = terrainData.GetAlphamaps(mapX, mapZ, 15, 15);

    for(var z = 0; z < 15; z++)
    {
        for(var x = 0; x < 15; x++)
        {
            // This ofcourse would be more efficient if you do this only once
            // e.g. in Awake since the enum won't change on runtime
            var values = (TerrainLAyer[])Enum.GetValues(typeof(TerrainLayer));

            // Iterate through the enum and 
            for(var l = 0; l < values.Length; l++)
            {
                // set all layers to 0 except the toLayer
                splatmapData[x, z, l] = values[l] == toLayer ? 1 : 0;
            }
        }
    }

    terrainData.SetAlphamaps (mapX, mapZ, splatmapData);
    terrain.Flush ();
}

现在您可以简单地称呼它,例如

ChangeTexture(somePosition, TerrainLayer.Green);