THREE.JS - CAMERA MAGIC

In three.js, the camera is treated like an object, which means that you can attach the camera to other objects. This allows you to easily move the camera around the scene and to focus on (or away from) objects with very little code.

The Camera Alone - Looking Around

When using the camera alone, you can look around by rotating the camera using a global coordinate system. In this system, up and down movements are treated as changes in latitude, ranging from +90 degrees (north pole) to 0 degrees (equator) to -90 degrees (south pole). Left and right movements are treated as changes in longitude (or heading), rnanging from 0 degrees (north), to 90 degrees (east), to 180 degrees (south), to 270 degrees (west), back up to 360 or 0 degrees.

In general, you define the variables and the camera as follows:

let width  = window.innerWidth, height = window.innerHeight;
let aspect = width/height;
const camera = new THREE.PerspectiveCamera(45, aspect, 1, 10000);
    camera.rotation.order = "YXZ";
let CamLat, CamLon; // camera latitude and longitude

You can use the mouse or key inpt to read the change in CamLat and CamLon. You will want to limit CamLat to +/-90 since going beyond those values will cause the camera to flip, which would be disorienting. Once you have the new CamLat and CamLon values, you can use the following subroutine to set the camera rotation:

function roteCamera() {
    camera.rotation.x = CamLat * DegRad;
    camera.rotation.y = CamLon * DegRad;
}

where DegRad is the factor used to convert degrees to radians.

External View - Looking Inward

You can also link the camera to another object (camobj) which acts as a "selfie stick" and then attach that object to other objects of interest. This allows you to orbit the object of interest. To do this, you would add the following commands to the camera definiton:

const camobj = new THREE.Object3D();
    camobj.rotation.order = "YXZ";
    camobj.add(camera);
let CamDst = 100; // Camera distance from object of interest
let CamOut = 180; // Camera y-rotation

You would attach camobj to the object of interest, e.g.:

    airobj.add(camobj);

You would use the same input method to read the change in CamLat and CamLon. However, instead of rotating the camera, you would rotate camobj to change the position of the camera. You could use this kind of subroutine:

function moveCamera() {
    camera.position.z = -CamDst;
    camobj.rotation.x = Mod360(CamLat) * DegRad;
    camobj.rotation.y = Mod360(CamLon+CamOut)*DegRad;
}
Cockpit View - Looking Outward

You can also use the same routine to look outwards from an object, such as an aircraft cockpit. You would attach camobj to the object of interest, e.g.:

    airobj.add(camobj);

You would set CamDst to a small value, representing the distance of your eyes from your neck, e.g. .1, and you would change the value of CamOut to zero. You can then use the same input method to change the direction you are looking.