Checking distance between 2 objects (401117)

Hi.This is my first thread. How do I check the distance between the player controller and some other object in order to trigger off an event? Thanks.

How about you just use a trigger? If you’d still rather use distance, use Vector3.Distance.

–Eric

Something like this?

XDistance = Xlocation1 - Xlocation2
YDistance = Ylocation1 - YLocation2
ZDistance = ZLocation1 - ZLocation2

Distance = SquareRoot(XDistanceXDistance + YDistanceYDistance + ZDistance*ZDistance)

…Or you could just use Vector3.Distance. :slight_smile:

–Eric

True but being a Monkey with glasses i have to try to show that I know what’s behind Vector3.Distance. :slight_smile:

I Iz teh l33t.

You can also use a raycast between the player controller/main camera and whatever object you’re trying to measure. I definitely agree with Eric, though, Vector3.Distance is probably the simplest way to do it. I asked a similar question recently and at this point I wouldn’t do it any other way.

thanks all . i am new (yesterday) to this engine. Still feeling around.

I hope I’m not too late to offer something useful.

First, congrats on choosing Unity. I’ve never seen any other game development tool do what it can.

Second, this thread is technically in the wrong forum. For reference, something like this should go under “General” or “Scripting”, instead of “Gossip”. (since… you know… it’s not something one is likely to go tell their friends about. Although you never know…)

Third, and on topic, finding the distance between two points can be done with, as mentioned, Vector3.distance. However, for what you want, you need to take a couple of things into account:

  1. Finding square roots is computationally intensive. A simple way to avoid this is to use the Vector3.sqrMagnitude function and simply squaring the input. Huge performance boost right there, especially if you plan to use it in Update().

  2. As was also suggested, you could use a trigger. From the docs:

The messages that are “sent” (they work just like Update) are OnTriggerEnter, OnTriggerExit, and OnTriggerStay. Sounds like what you’re after.

Hope it helps.