How to extend OrbitControls and access its internal vars

camera-controls
typescript
orbit-controls

#1

Hi all,

I’m working in a ThreeJS project using TypeScript. I would like to extend THREE.OrbitControls and be able to access its internal properties and methods like spherical or dollyIn(), dollyOut() etc.

I tried this :

    class CameraControls extends THREE.OrbitControls {
    	constructor(object:THREE.Camera, domElement?:HTMLElement) {
    		super(object, domElement);
    		
    		let spericalValue:number = this.spherical.phi;
    	}
    }

But “spherical” is undefined.

I’ve tried several methods to extend it, even in pure JS (not TypeScript), but no luck. Any help would be appreciated.


#2

The variable spherical is internal or private. This is also true for functions like dollyIn() or dollyOut(). You can only change this fact if you modify OrbitControls.


#3

Hi, thanks for your quick reply. I was afraid that would be the answer. I try to avoid modifying libraries because they are a pain to mantain (you have to re-apply your own changes to the new versions every time you update them).
It would be nice of those properties where protected or public so they can be used from extending classes.

So far I´ve solved it by adding this to OrbitControls:

	this.getSpherical = function() {
		return spherical;
	}
	this.getSphericalDelta = function() {
		return sphericalDelta;
	}
	this.setDollyIn = function(dollyScale) {
		dollyIn(dollyScale);
	}
	this.setDollyOut = function(dollyScale) {
		dollyIn(dollyScale);
	}

Then, on my extending class in TypeScript I have:

	setPolarAngle(angle:number, updateCamera:boolean = true):void {
		if (angle == undefined || isNaN(angle)) return;
		this.getSphericalDelta().phi = this.getSpherical().phi - angle;
		if (updateCamera) this.update();
	}
	setAzimuthalAngle(angle:number, updateCamera:boolean = true):void {
		if (angle == undefined || isNaN(angle)) return;
		this.getSphericalDelta().theta = this.getSpherical().theta - angle;
		if (updateCamera) this.update();
	}
	setDollyScale(dollyScale:number, updateCamera:boolean = true) {
		if (dollyScale == undefined || isNaN(dollyScale)) return;
		// If positive number, dolly in, else dolly out.
		if (dollyScale > 0) {
			this.setDollyIn(dollyScale);
		} else {
			this.setDollyOut(Math.abs(dollyScale));
		}
		if (updateCamera) this.update();
	}

Maybe not the best code in the world, but works for me. I hope it helps somebody else.