-
Notifications
You must be signed in to change notification settings - Fork 0
/
TerrainInfoHelper.cs
64 lines (60 loc) · 1.97 KB
/
TerrainInfoHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using UnityEngine;
public class TerrainInfoHelper
{
private static float[] GetTextureMix(
Vector3 worldPos)
{
// returns an array containing the relative mix of textures
// on the main terrain at this world position.
// The number of values in the array will equal the number
// of textures added to the terrain.
var terrain = Terrain.activeTerrain;
var terrainData = terrain.terrainData;
var terrainPos = terrain.transform.position;
// calculate which splat map cell the worldPos falls within (ignoring y)
var mapX = (int) (((worldPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
var mapZ = (int) (((worldPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);
// get the splat data for this cell as a 1x1xN 3d array (where N = number of textures)
var splatmapData = terrainData.GetAlphamaps(
mapX,
mapZ,
1,
1);
// extract the 3D array data to a 1D array:
var cellMix = new float[splatmapData.GetUpperBound(
2) + 1];
for (var n = 0; n < cellMix.Length; ++n)
{
cellMix[
n
] = splatmapData[
0,
0,
n
];
}
return cellMix;
}
public static int GetMainTexture(
Vector3 worldPos)
{
// returns the zero-based index of the most dominant texture
// on the main terrain at this world position.
var mix = GetTextureMix(
worldPos);
float maxMix = 0;
var maxIndex = 0;
// loop through each mix value and find the maximum
for (var n = 0; n < mix.Length; ++n)
{
if (!(mix[
n
] > maxMix)) continue;
maxIndex = n;
maxMix = mix[
n
];
}
return maxIndex;
}
}