OrbitControls with simplified lookAt()

by Lukasz Guminski

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/98/three.min.js"></script>
<script src="https://threejs.org/examples/js/renderers/CSS2DRenderer.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<div id="info">Click on object to make it the target of Object3D.lookAtObject3D</div>

CSS

body {
  margin: 0;
}

#info {
  position: absolute;
  left: 1em;
  top: 1em;
  background: rgba(0, 0, 0, .8);
  padding: .5em;
  color: white;
  font-family: monospace;
}

JavaScript

THREE.Object3D.prototype.lookAt = function () {

  var q1 = new THREE.Quaternion();
  var m1 = new THREE.Matrix4();
  var vector = new THREE.Vector3();
  var target = new THREE.Vector3();
  var position = new THREE.Vector3();

  return function lookAt(x, y, z) {

    if (x.isVector3) {
      target.copy(x);
    } else {
      target.set(x, y, z);
    }

    this.updateMatrix();
    position.setFromMatrixPosition(this.matrix);

    if (this.isCamera) {
      m1.lookAt(position, target, this.up);
    } else {
      m1.lookAt(target, position, this.up);
    }

    this.quaternion.setFromRotationMatrix(m1);
  };
}();


THREE.Object3D.prototype.lookAtObject3D = function () {

		var m1 = new THREE.Matrix4();
		var position = new THREE.Vector3();
		var parentMatrix;
		return function lookAtObject3D( object ) {
			object.updateWorldMatrix( true, false );
			if ( this.parent ) {
				this.parent.updateWorldMatrix( true, false );
				parentMatrix = this.parent.matrixWorld;
			} else {
				parentMatrix = m1.identity();
			}
			m1
				.getInverse( parentMatrix )
				.multiply( object.matrixWorld );
			position.setFromMatrixPosition( m1 );
			this.lookAt( position );
		};
}();

var camera, fakeCamera, controls, scene, renderer, labelRenderer, raycaster;
var angle1 = Math.PI;
var angle2 = 1/3 * Math.PI;
var solarPlane, planetA, planetB, moonA1, moonA2, moonB1;

var p = new THREE.Vector3();
var q = new THREE.Quaternion();
var s = new THREE.Vector3();

var target;
init();
animate();

function createSolarPlane() {
  var solarPlane = new THREE.GridHelper(5, 10);
  solarPlane.add(makeTextLabel("solar plane"));
  return solarPlane;
}

function createLine() {
  var lineMaterial = new THREE.LineBasicMaterial({
    color: "white"
  });
  const geometry = new THREE.Geometry();
  const line = new THREE.Line(geometry, lineMaterial);
  line.geometry.vertices[0] = new THREE.Vector3();
  line.geometry.vertices[1] = new THREE.Vector3(0, 0, 10);
  line.geometry.verticesNeedUpdate = true;
 ...