gl-matrix

Retrieve center point the viewer is looking at from view/perspective matrix


I use the glMatrix's method: mat4.lookAt(out, eye, center, up) to set a camera view when a WebGL model is rendering.

After the model is rendered, I need to retrieve the center attribute from view/perspective matrix. I know how to retrieve the eye attribute, but I have no idea how to get the center one. How can I do that?

This is the mat4.lookAt method I use: http://glmatrix.net/docs/mat4.js.html#line1366


Solution

  • you can't get the actual center since it was normalized. You can get a center position that will generate the same look at. I think it would be this.

    camera = mat4.inverse(mat4.create(), view);
    up = camera.slice(4, 7);
    eye = camera.slice(12, 15);
    negativeZ = camera.slice(8, 11);
    center = vec3.scaleAndAdd(vec3.create(), eye, negativeZ, -1);
    

    That center will be one unit in front of the eye. Change the -1 to -1 * units to make it further away from the eye. In other words -2 would be two units in front, -3 would be 3 units in front etc.

    Here's a test

    const eye = [1, 2, 3];
    const center = [4, 5, 6];
    const up = [0, 1, 0];
    const view = mat4.lookAt(mat4.create(), eye, center, up);
    
    const camera = mat4.invert(mat4.create(), view);
    const newUp = camera.slice(4, 7);
    const newEye = camera.slice(12, 15);
    const negativeZ = camera.slice(8, 11);
    const newCenter = vec3.scaleAndAdd(vec3.create(), newEye, negativeZ, -1);
    
    const newView = mat4.lookAt(mat4.create(), newEye, newCenter, newUp);
    
    // show difference between view and newView
    console.log(view.map((v, i) => (v - newView[i]).toFixed(6)));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.4.0/gl-matrix-min.js"></script>

    This article explains the parts of a camera matrix and what a view matrix is.