Threejs: Distance from camera to object

2020.10.19 | 201 words |

problem

I’m using threejs to build out an audiovisualizer to accompany the release of an audio track. As part of this, I’m trying to figure out how to find the distance from the camera to a specfic object. How can I get the distance between my main camera and a given object I’ve created in Threejs?

solution

The Vector3.distanceTo function is very useful for this use case. All objects in threejs that have a ‘location’ will have a position property on them that stores their position in Vector3 format.

Thus to find the distance between two threejs objects with position, we can do something like:

let distance = objectA.position.distanceTo(objectB.position)

This will spit out the distance between objectA’s position and objectB’s position.

We can then extend this to cover the usecase of finding the distance between the camera and an object. In threejs, a camera is just another object in the scene and it, too, has a position attached to it.

So we can find the distance between the camera and another object in the same way we did it for two objects:

let distanceBetweenCameraAndObject = camera.position.distanceTo(someObject.position)

This will spit out the distance between the camera’s position vector and someObject’s position vector.

 

About the Ham

Hi I'm Hamilton - I built this! If you want more content like this subscribe to my email list, connect with me around the web, or take a look at some of my other projects.

More Projects

comments powered by Disqus