Game Development Reference
In-Depth Information
However, this is not what we want. We placed our right hand right in front of our
eyes/camera. Actually, our right hand is placed to the right (x=1), below (y=-3), and
behind(z=-8) the camera/screen. Therefore, we need to apply a translation as shown
in the following code:
var mMatrix=mat4.clone(cam.viewMatrix);
mat4.invert(mMatrix,mMatrix);
mat4.translate(mMatrix,mMatrix,vec3.fromValues(1,-3,-8));
mat4.multiply(mvMatrix,mvMatrix,mMatrix);
Hence, we moved our hand to the right (x = 1 unit), below (y = -3 units), and behind
(z = -8 units) with respect to our camera.
Let's reiterate the steps that we need to perform to position any object with respect to
our camera:
1.
Get the camera view matrix.
2.
Calculate the camera matrix by getting the inverse of the view matrix.
3.
Apply transformations to the camera matrix to place the object with respect
to the camera.
4.
Multiply the transformed camera matrix to the ModelView matrix.
Improving the first-person camera code
The preceding code is in the
drawScene
function. If we have to apply different types
of transformations to every object in our scene, then our
drawScene
function would
become very big, and this is not what we want. Hence, we decided to create another
code update. We added two new functions to our
StageObject
class.
Open the
StageObject.js
file from the
primitive
folder of the code bundle in your
text editor.
We defined a new variable
modelMatrix
to hold the object's model matrix, as shown
in the following code:
this.modelMatrix=mat4.create();
Then, we added a new function
StageObject.prototype.update
. This function is
invoked by
drawScene
to calculate the model matrix, as shown in the following code:
StageObject.prototype.update=function(steps){
mat4.identity(this.modelMatrix);
mat4.translate(this.modelMatrix,this.modelMatrix, this.location);
mat4.rotateX(this.modelMatrix,this.modelMatrix,this.rotationX);
mat4.rotateY(this.modelMatrix,this.modelMatrix,this.rotationY);
mat4.rotateZ(this.modelMatrix,this.modelMatrix,this.rotationZ);
}