Game Development Reference
In-Depth Information
To perform the preceding operations, we have added a function,
unProjectVector
,
to our
camera
class and a general purpose
applyProjection
function in
utils.js
.
Open the
utils.js
file in your favorite editor. The following code snippet is present
in this file:
function applyProjection(vector,m){
var x = vector[0], y = vector[1], z = vector[2];
var e = m;
var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] );
// perspective divide
var x1 = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
var y1 = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
var z1 = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
return vec3.fromValues(x1,y1,z1);
}
The preceding function,
applyProjection
, takes a vector (
vec3
) and matrix as
parameters. It first calculates the
w
component (
var d = 1 / ( e[3] * x + e[7]
* y + e[11] * z + e[15] );
), then multiplies each component,
x1
,
y1
, and
z1
,
with it to get the normalized vector.
Open the
camera.js
file from the
primitive
folder in your editor to understand our
new function,
unProjectVector
:
Camera.prototype.unProjectVector=function(vector){
var inverseProjection=mat4.create();
mat4.invert(inverseProjection,this.projMatrix);
var viewProjection=mat4.create();
mat4.invert(viewProjection,this.viewMatrix);
mat4.mul(viewProjection,viewProjection,inverseProjection)
var vec=applyProjection(vector,viewProjection);
return vec;
}
In the preceding code, we first calculate our inverse projection matrix
inverseProjection
. We then calculate our inverse ModelView matrix and multiply
them to get our
viewProjection
matrix.
viewProjection
= M-1 * P-1
Now we multiply our
viewProjection
matrix with the vector using our function
a
pplyProjection
, which also performs the perspective divide.