Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created October 18, 2017 18:37
Show Gist options
  • Save unity3dcollege/f4e7b3fdb95210561580a0d14c4c4f8a to your computer and use it in GitHub Desktop.
Save unity3dcollege/f4e7b3fdb95210561580a0d14c4c4f8a to your computer and use it in GitHub Desktop.
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;
}
}
@ziplock9000
Copy link

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?

@benthroop
Copy link

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