Focal point camera based on position and heading


This example shows you how to get the proper heading and position for two camera's based on a single position and heading. For context, in a first person environment you basically have a camera that has a (single) position. If you want to turn that into two camera's for stereoscopic view, or just for shits and giggles, I'll show you an example of how to do that.

I'll do the example in 2d, you can upscale that yourself if you need to.

So we have a position and a heading which is the angle that tells us which direction exactly we are looking. The heading is not where we are moving to because that'd be the bearing. So heading. Looking.

You'll need to define how far from the point the camera's should be. They'll go the same distance, opposite from each other, perpendicular to the heading. Let's put it this way; the point represents your nose and we need to determine where your eyes actually go.

From those two points we determine a so called "focal point". That's the distance from the "nose" (the main point) that you want to have focused. There's some straightforward trigonometry involved here.

// config
var focalDistance = 50;
var cameraDistance = 40;
var cx = 150;
var cy = 75;
var heading = 270 /180*Math.PI; // up

// get to left cam
var lx = cameraDistance * Math.cos(heading-0.5*Math.PI);
var ly = cameraDistance * Math.sin(heading-0.5*Math.PI);

// delta angle from left cam straight to focal (add to heading!)
// basically: absLeftCamHeading = heading + (90 - camAngleToFocus)
var dangle = 0.5 * Math.PI - Math.atan(focalDistance / cameraDistance);

// line from camera through focus point
var fx = 2 * focalDistance * Math.cos(heading + dangle);
var fy = 2 * focalDistance * Math.sin(heading + dangle);
// or exactly to focal point using pythagoras
var camd = Math.sqrt(cameraDistance * cameraDistance + focalDistance * focalDistance);
var fx = camd * Math.cos(heading + dangle);
var fy = camd * Math.sin(heading + dangle);

// pretty much same idea for right, except we subtract dangle
var rx = cameraDistance * Math.cos(heading+0.5*Math.PI);
var ry = cameraDistance * Math.sin(heading+0.5*Math.PI);
// note: focal point coordinate will not have changed ;) so still fx/fy

Live "dumb" example (or this fiddle):

An interactive version (slightly more complex because it has to compute mouse coords back to form a heading...). Move. Your. Mouse. (fiddle):