distance between two objects

How do I determine what action is needed from the distance between two gameobjects.

For example…if player shoots at the target and too far from it…it will send a message. Whereas if the target is close within range…it will shoot.

I apologize ahead of time for not clarifying myself. I hope you guys know what I’m trying to say.

Thanks.

if (Vector3.Distance(object1.transform.position, object2.transform.position) < someValue) {
//it's within range
}
else {
//it's not
}

ok i understand the script but what is someValue equals to in term of…is it pixels or what?

Sorry for being such a novice.

Thanks.

a distance is usually going to be measured in game units, which are meters by convention (but can be anything with adjustments to things like gravity)

Thank you Charles. I guess I can test it out by replacing someValue with a number and see how far that is from the target.

Another way is to use the magnitude method:

var diff = objB.transform.position - objA.transform.position;
var distance = diff.magnitude;
// or just
distance = (objB.transform.position - objA.transform.position).magnitude;

If you create a cube in Unity then that cube sides are 1 unit long. Thus you can scale it and the lengths will always match the scale in units. Very useful the get a feeling for how big/small objects are.

ah thank you for the tip Adrian and I will definitely try both yours and StarManta script when I get a chance.

Thanks.

Using Vector3.Distance does the exact same thing as the magnitude method behind the scenes, so there’s no difference; it’s just easier to remember. One reason to use the latter, though, would be to substitute “.sqrMagnitude” for “.magnitude”, which is quite a bit faster since it doesn’t have to do a square root. This gives you the square distance instead, of course, but that can still be useful in many cases. So if it’s something you’re checking every frame, try to use the sqrMagnitude method where possible instead of Vector3.Distance.

–Eric

Another thing to consider is that when you subtract one vector from another, you get a new vector that can be added back to the second vector to arrive at the first (I hope I didn’t flip the order of that, I haven’t had coffee yet and my thinking is really cloudy).

Why is this important? Well, the magnitude of this second vector is the distance between them, and this vector also contains directional information between them, so if you will ultimately be doing anything with that information (whether firing a projectile or determining the degree of alignment or moving the character or whatever) simple subtraction can simplify things.

Also, Eric’s advice is good – it isn’t a major optimization for things that aren’t happening in a loop, but getting in the habit of comparing sqrMagnitude to a value times itself (a square distance limit), when appropriate, is probably a good thing.