x


how to get the distance (or altitude) of one object above another

I'm trying to get the height of my ship above the ground (altitude if you like) at the moment I'v tried this

var HeightTXT: GUIText;
var Heighttarget : Transform;
var distance : int;

function Update() {
    var distance = Vector3.Distance(transform.position, Heighttarget.position);
    HeightTXT.text = "height = " + distance;
}

but I'm getting the distance to the center of the object (imagine a big flat plane for the ground) I'm after something like height above sea level, the distance from my ship to the ground plane

more ▼

asked Jan 18 '10 at 02:41 PM

mikevanman gravatar image

mikevanman
43 6 8 11

edited title for clarity, and formatted code

Jan 18 '10 at 02:57 PM duck ♦♦
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

If you want just the height from the centre of your object to the ground plane (presumably this is what is stored in your var "Heighttarget"), you just need to compare the Y component of the position variables. Eg:

var distance = transform.position.y - Heighttarget.position.y;

However if your object is of significant size, you might want the distance from the bottom of your object to the ground plane. In this case you can use Renderer.bounds to find the extremities of your object along each axis. In particular, renderer.bounds.min.y will give you the lower y level of your object in world space.

Here's an adaptation of your script:

var HeightTXT: GUIText;
var Heighttarget : Transform;
var distance : int;

function Update() {
    var distance = renderer.bounds.min.y - Heighttarget.position.y;
    HeightTXT.text = "height = " + distance;
}

And finally, if your ground isn't a flat plane (eg, hilly terrain), and you want the distance to the ground that's currently under your object rather than the distance to a fixed height (like sea-level), you'll need to use a Ray Cast (either Physics.Raycast or Collider.RayCast) each frame to determine the current height.

more ▼

answered Jan 18 '10 at 02:45 PM

duck gravatar image

duck ♦♦
41k 92 148 415

works a charm, and that was quick I just got back from making tea...

I'll also try the Raycast version cheers again

Jan 18 '10 at 03:20 PM mikevanman
(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:

x212

asked: Jan 18 '10 at 02:41 PM

Seen: 2369 times

Last Updated: Jan 18 '10 at 02:58 PM