- Home /
How can I get the distance between two objects?
Hello. How can I get the distance between two (moving) objects and then have a function dependent on the distance (ex: if distance > 10...)? Thanks
Answer by The_r0nin · Dec 23, 2010 at 08:38 PM
var obj1 : Transform; var obj2 : Transform;
function Update() { var distance = Vector3.Distance(obj1.position, obj2.position); if (distance > 10.0f) { // do your code here } }
Though, in terms of performance, you might be better off using the square of your distance (fewer square roots to calculate) and do something like:
var sqrDistance = (obj1.position - obj2.position).sqrMagnitude;
// Note you also need to calculate the square of the test, // so 100.0f = 10.0f * 10.0f if (sqrDistance > 100.0f) { // do your code here }
I took the liberty to tidy up your answer and clarify the 100.0f distance. Well thought with the performance.
any idea on how to display the distance in the scene. distance consider in km or pix.?? somethings
Answer by Mickydtron · Dec 23, 2010 at 08:33 PM
Vector3.Distance(transform.position, othertransform.position);
will return the distance between the position of this object and the position of the object that we have assigned othertransform to. We could use this in code (javascript) like such:
var othertransform : Transform;
function Awake() { othertransform = GameObject.FindWithTag("Target").transform; }
function Update() { if (Vector3.Distance(transform.position, othertransform.position) > 10) { DoSomething(); } }
Update is called each frame, so it will always have an accurate distance reading.
there's no need to reset the Transform if you set it in the Inspector.
That is true, you could set it in the Inspector. I always forget about that. Probably comes from my program$$anonymous$$g background. Dragging and dropping is too primitive. :)
@$$anonymous$$ikeydtron : http://notinventedhe.re/on/2010-12-21 :)
any idea on how to display the distance in the scene. distance consider in km or pix.?? somethings
Answer by Jesus_Freak · Dec 23, 2010 at 08:34 PM
just put a distance function in the function Update, and also do a if(distance > 10) in the function Update.
so something like
var that : Transform;
function Update()
{
var distFromPlayer = Vector3.Distance(that.position, transform.position)
if(distFromPlayer > 10)
{
//do more stuff here.
}
}
i think might work.
Vector3.Distance(a,b) return a float value, not another Vector3. It is just a distance, not the difference vector.
Your answer
![](https://koobas.hobune.stream/wayback/20220613092328im_/https://answers.unity.com/themes/thub/images/avi.jpg)