How to calculate the distance between 2 meshes in ThreeJS

When I was playing with ThreeJS, I was wondering how to calculate the distance between 2 meshes in ThreeJS, without raycasting, collision detections and so on.

Because if you use these ways, you only get the distance if there is a collision and it’s quite expensive with the raycasting technique.

How to calculate the distance between 2 meshes in ThreeJS

Just with the meshes’ positions

function getDistance(mesh1, mesh2) { 
  var dx = mesh1.position.x - mesh2.position.x; 
  var dy = mesh1.position.y - mesh2.position.y; 
  var dz = mesh1.position.z - mesh2.position.z; 
  return sqrt(dx*dx+dy*dy+dz*dz); 
}

You can also apply this function to any framework, just keep in mind that they are 3D objects with the three coordinates: x, y and z.

Leave a comment if you have a doubt or suggestion 🙂

David Burgos

Read more posts by this author.