How to *set* (not increment) OrbitControls distance from target programmatically?

764 Views Asked by At

I'm trying to adjust the ThreeJS OrbitControls so that I can set the distance from the target programmatically.

https://github.com/mrdoob/three.js/blob/master/examples/jsm/controls/OrbitControls.js

The goal is to be able to call it like this:

const controls = new THREE.OrbitControls(camera);
controls.setDolly(1); // Near
controls.setDolly(10); // Far

A setDolly method doesn't exist, so I've adjusted the OrbitControls.js script, and have added:

this.setDolly = function(newDolly) {
    spherical.radius = newDolly;
};

However, due to some way that OrbitControls has been written that I don't understand, the camera does not budge.

Does anyone know what the problem is?

1

There are 1 best solutions below

0
On

You can try this custom function I wrote like this:

function setDolly(value){
    let positive = Math.abs(value); //Absolute value to prevent negative increments
    camera.position.set(1, 1, 1); //Default of 1 so it dollys to the desired position

    //Moving camera.
    camera.position.x *= positive;
    camera.position.y *= positive;
    camera.position.z *= positive;
};

It would be easier to add this to your code instead of OrbitControls.js, because then you would need to make some substantial changes.

That should do it~