x


Get terrain position from world position

Hi,

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?

more ▼

asked Sep 12 '10 at 07:08 AM

Noam gravatar image

Noam
282 24 24 33

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Sep 12 '10 at 07:42 AM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

Works as expected. Thanks!

Sep 12 '10 at 08:14 AM Noam
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5086
x1879
x1478

asked: Sep 12 '10 at 07:08 AM

Seen: 2955 times

Last Updated: Sep 12 '10 at 07:08 AM