Last active
August 30, 2022 14:33
-
-
Save Bradshaw/27344331c24b369bb2416e9739680a53 to your computer and use it in GitHub Desktop.
Example of detection of terrain texture at position
This file contains hidden or 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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class GetMainTextureThing : MonoBehaviour | |
{ | |
TerrainData mTerrainData; | |
int alphamapWidth; | |
int alphamapHeight; | |
float[,,] mSplatmapData; | |
int mNumTextures; | |
void Start() | |
{ | |
mTerrainData = Terrain.activeTerrain.terrainData; | |
alphamapWidth = mTerrainData.alphamapWidth; | |
alphamapHeight = mTerrainData.alphamapHeight; | |
mSplatmapData = mTerrainData.GetAlphamaps(0, 0, alphamapWidth, alphamapHeight); | |
mNumTextures = mSplatmapData.Length / (alphamapWidth * alphamapHeight); | |
} | |
private Vector3 ConvertToSplatMapCoordinate(Vector3 playerPos) | |
{ | |
Vector3 vecRet = new Vector3(); | |
Terrain ter = Terrain.activeTerrain; | |
Vector3 terPosition = ter.transform.position; | |
vecRet.x = ((playerPos.x - terPosition.x) / ter.terrainData.size.x) * ter.terrainData.alphamapWidth; | |
vecRet.z = ((playerPos.z - terPosition.z) / ter.terrainData.size.z) * ter.terrainData.alphamapHeight; | |
return vecRet; | |
} | |
void Update() | |
{ | |
int terrainIdx = GetActiveTerrainTextureIdx(); | |
name = "Current terrain: "+terrainIdx; | |
} | |
int GetActiveTerrainTextureIdx() | |
{ | |
Vector3 playerPos = transform.position; | |
Vector3 TerrainCord = ConvertToSplatMapCoordinate(playerPos); | |
int ret = 0; | |
float comp = 0f; | |
for (int i = 0; i < mNumTextures; i++) | |
{ | |
if (comp < mSplatmapData[(int)TerrainCord.z, (int)TerrainCord.x, i]) | |
comp = mSplatmapData[(int)TerrainCord.z, (int)TerrainCord.x, i]; | |
ret = i; | |
} | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this! There's a bug you might want to fix:
should be