Search code examples
three.jsreact-three-fiber

change the distance of a 3dObject from another 3Object in threejs


Is there any way to change the distance of the camera from a fixed 3Object in threejs?

There is a "Vector3.distanceTo(Vector3)" function that gives you the distance of two 3d objects but I couldn't find anything that changes the distance.


Solution

  • There is no function that can do this for you. If you want to change the position of a 3D object, you have to translate it by modifying its position property.

    Assuming you want to keep the directon between both 3D objects, you can implement the code like so:

    const a = new THREE.Object3D();
    a.position.set(0, 0, 0);
    
    const b = new THREE.Object3D();
    b.position.set(0, 0, 1);
    
    console.log(a.position.distanceTo(b.position)); // 1
    
    // move object "b" 2 additional world unit away from object "a"
    
    const direction = new THREE.Vector3();
    direction.subVectors(b.position, a.position).normalize();
    
    const offset = new THREE.Vector3();
    offset.copy(direction).multiplyScalar(2);
    
    b.position.add(offset);
    
    console.log(a.position.distanceTo(b.position)); // 3
    body {
        margin: 0;
    }
    <script src="https://cdn.jsdelivr.net/npm/three@0.141/build/three.min.js"></script>
    This code snippet assume both 3D objects have no ancestors nodes.