- Home /
Incorrect height with sampleHeight
The case is: I have cube which I want to move along a non-flat terrain just by setting the cube.position.y = the height of terrain below the cube. All this with C#.
I was adviced to use sampleHeight but after trying dozens of different forms and even javascript the height was never correct.
By the way even the "Terrain.SampleHeight" example (as C#) in Unity API gives an error BUT I managed to get it working (but with incorrect height) like this:
height = Terrain.activeTerrain.SampleHeight(cube.position);
cube.position = new Vector3(cube.position.x, height, cube.position.z);
With this piece of code, during the game if I move the cube around the terrain, it's always 22 units too high on y axis. Of course I could just add -22 to the height but why it's incorrect in the first place? Is there something wrong with the code because I had to find it out myself?
Answer by Statement · Dec 07, 2010 at 03:45 PM
There is nothing wrong with SampleHeight. If you read the docs, it says the value is in terrain space. The reason you're having 22 as your magic number is probably because your terrain is located 22 units away from the world origin.
Try to use this instead:
height = Terrain.activeTerrain.SampleHeight(cube.position)
+ Terrain.activeTerrain.transform.position.y;
Yes! That's it! Good lord I got it finally working. $$anonymous$$y terrain was apparently a child of my 'scene' -empty object so I had probably moved it sometime. Thank you!
Now carry on and make great wonders with this new technology :)
Interestingly I found out that both $$anonymous$$e and your example works but my code drops the fps from 215 down to 80 and yours not at all. I'd like to know what $$anonymous$$e does too much without the "+ Terrain.activeTerrain.transform.position.y; " -part. After all isn't it just getting y from x,y,z position? I don't understand how does adding additional y make it any faster.
Your answer
Follow this Question
Related Questions
Character height issue 0 Answers
Raise/Lower terrain height? - javascript. 1 Answer
How to stop at a point of axis? 1 Answer