- Home /
The question is answered, right answer was accepted
Following Terrain Height?
EDIT: THE PROBLEM IS HIT.DISTANCE AS IT KEEPS CHANGING. I need it to be dynamic, but not be 2 things at once.
Is there a way to make an object go all the way down on the Y axis until it hits the terrain? As well as rotate with the curves?
I do not even know where to start with it , also I use javascript instead of C#, as I do not really know c#.
Extra info: I am instantiating an object, but using the code below, it just starts flickering from the instantiated place to the area the code calls for. The code below is all that is attached to the instantiated object.
Here is the code:
function Update () { var HighestPointOfTerrain : int = 50; var hit : RaycastHit; if(Physics.Raycast(transform.position, -Vector3.up, hit)) { var distancetoground = hit.distance; var heightToAdd = transform.localScale.y; transform.position.y = HighestPointOfTerrain - distancetoground+ heightToAdd; } }
If you are looking for having it stay flush with the terrain, you will want to add a rigidbody component to the object.
So then what is the problem? If the object has physics, it should stay on flush with the terrain automatically.
I don't know any other way of saying that it flickers in two places
By 'flickers' do you mean that is moving to multiple positions very rapidly?
I think the issue might be with the script moving the object to a bad location and then the physics engine pushes the object out of that location, the script puts it in another bad spot, and so on.
Answer by rabbitfang · Jan 02, 2012 at 07:42 AM
Try changing the line
transform.position.y = HighestPointOfTerrain - distancetoground+ heightToAdd;
to
transform.position.y = transform.position.y - distancetoground + heightToAdd;
Basically, what was happening was you were assuming that your object was always at a height of HighestPointOfTerrain
(at least, that is what the code was doing), which caused your calculations to get messed up.
Then please mark my answer as correct (look for the check mark).
Answer by kievar1983 · Jan 02, 2012 at 08:01 AM
are you looking to put an actual object on the ground or is this like a targeting box or something along those lines that you want to simply project onto the terrain. if it's the second idea, you might want to look into projections.
http://unity3d.com/support/documentation/Components/class-Projector.html
The previous answer got what I needed. Works like a charm now :).