Beginner B21 – Finding Distance with Vector3
Finding the distance between two points in 3D space using Vector3.Distance command
Code Used (Javascript)
-
var box : Transform;
-
-
function Update () {
-
-
var dist : float = Vector3.Distance(box.position, transform.position);
-
Debug.Log(dist);
-
-
if(dist <= 10){
-
light.enabled = true;
-
}else{
-
light.enabled = false;
-
}
-
}
Further Reading
5 Comments
Leave a Comment









While Distance( … ) is good, it is mathematically expensive- The alternative approach is taking the squared magnitude, or the summed magnitude of it’s components, then forgoing the final root for distance, which cuts out the most expensive mathematical element of it, but gives you a return that is valid in terms of comparison. To do this in the above example, you would use (box.postion – transform.position).sqrMagnitude
Another optimization would be to cache the objects Transform, by setting a private variable during Awake (Because transform always does a GetComponent(Transform), which takes allot longer then if you know what transform your using)
Quick question, does the DistCheck script that you dragged on to the point light contain the same coding as the lightSwitch script you work on during the video?
ERROR SPOTTED! WELL DONE! Hey everyone thanks to eagle eyed Charlotte (not to be confused with Cherry) who spotted my mistake of dragging the wrong – albeit identically coded DistCheck instead of the lightSwitch script written in the video. The ‘DistCheck’ script is the same – just one i’d written in a practice before recording the video and forgotten to delete – my bad sorry! If I have time I’ll re-record this..
Quality work, I am impressed of the detail and Work that you, and yours:) have put on this project and Wish You the Best,
Sorry: these comments allow HTML, didn’t realise.
< is shown as & l t ; without all the spaces.
Delete my other one.