I would like to use TerrainData's GetInterpolatedHeight/Normal methods, but they require values in the 0..1 range. For that, I need to normalize my world coordinates (x,z of course) to the 0..1 range, but don't know exactly how to. Where am I supposed to get the total terrain width/height from. Also, is the terrain's transform position its center or one of its corners?
Basically, I want to transform from world space to terrain space. Any snippet on doing that?
You get the terrain size from TerrainData.size. The transform.position is the lower left corner (you can see this by the pivot point when a terrain is selected). Mathf.InverseLerp is good for this sort of thing:
var terrain : Terrain;
var worldPos : Vector3;
function Start () {
var terrainLocalPos = worldPos - terrain.transform.position;
var normalizedPos = Vector2(Mathf.InverseLerp(0.0, terrain.terrainData.size.x, terrainLocalPos.x),
Mathf.InverseLerp(0.0, terrain.terrainData.size.z, terrainLocalPos.z));
var terrainNormal = terrain.terrainData.GetInterpolatedNormal(normalizedPos.x, normalizedPos.y);
Debug.Log (terrainNormal + " " + normalizedPos.x + " " + normalizedPos.y);
}
Note that Terrain.SampleHeight uses world space and not normalized coords, so you might as well use that instead of TerrainData.GetInterpolatedHeight, since it's the same thing.