Created
October 18, 2017 18:37
-
-
Save unity3dcollege/f4e7b3fdb95210561580a0d14c4c4f8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class TerrainDetector | |
{ | |
private TerrainData terrainData; | |
private int alphamapWidth; | |
private int alphamapHeight; | |
private float[,,] splatmapData; | |
private int numTextures; | |
public TerrainDetector() | |
{ | |
terrainData = Terrain.activeTerrain.terrainData; | |
alphamapWidth = terrainData.alphamapWidth; | |
alphamapHeight = terrainData.alphamapHeight; | |
splatmapData = terrainData.GetAlphamaps(0, 0, alphamapWidth, alphamapHeight); | |
numTextures = splatmapData.Length / (alphamapWidth * alphamapHeight); | |
} | |
private Vector3 ConvertToSplatMapCoordinate(Vector3 worldPosition) | |
{ | |
Vector3 splatPosition = new Vector3(); | |
Terrain ter = Terrain.activeTerrain; | |
Vector3 terPosition = ter.transform.position; | |
splatPosition.x = ((worldPosition.x - terPosition.x) / ter.terrainData.size.x) * ter.terrainData.alphamapWidth; | |
splatPosition.z = ((worldPosition.z - terPosition.z) / ter.terrainData.size.z) * ter.terrainData.alphamapHeight; | |
return splatPosition; | |
} | |
public int GetActiveTerrainTextureIdx(Vector3 position) | |
{ | |
Vector3 terrainCord = ConvertToSplatMapCoordinate(position); | |
int activeTerrainIndex = 0; | |
float largestOpacity = 0f; | |
for (int i = 0; i < numTextures; i++) | |
{ | |
if (largestOpacity < splatmapData[(int)terrainCord.z, (int)terrainCord.x, i]) | |
{ | |
activeTerrainIndex = i; | |
largestOpacity = splatmapData[(int)terrainCord.z, (int)terrainCord.x, i]; | |
} | |
} | |
return activeTerrainIndex; | |
} | |
} |
At Line 17 you call GetAlphaMaps and cache the data into a float array. Is there no way to directly access the data within the terrain instead of duplicating some of the data?
This is for speed. GetAlphaMaps is slow and you don't want to do it with each footstep.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
At Line 17 you call GetAlphaMaps and cache the data into a float array. Is there no way to directly access the data within the terrain instead of duplicating some of the data?