Game Development Reference
In-Depth Information
Now, we need to move the camera with our arm or move the arm with our camera.
We will do the latter, which means that our arm should move as the camera moves.
We took this approach as we have already implemented a free camera class in
Chapter 5
,
Camera and User Interaction
, and we already control it with our keys.
As discussed in
Chapter 5
,
Camera and User Interaction
, the camera transformation
matrix is the same as any model matrix; so, if the camera was a model, then it would
have the same transformation as the camera. We compute the view matrix using the
mat4.lookat
function. We also discussed in
Chapter 5
,
Camera and User Interaction
, in
the
Converting between the camera matrix and view matrix
section, that the model matrix
(camera matrix) is the inverse of the view matrix, M=V
-1
.
Hence, to get the position of our arm, all we need to do is compute the camera matrix
and apply the transformation to the right-hand arm object, and that is it.
var mMatrix=mat4.clone(cam.viewMatrix);
mat4.invert(mMatrix,mMatrix);
Adding the first-person camera
Open
06-Bullet-Action.html
in your text editor.
The first change we do is load our right hand model as shown in the following code:
function start() {
...
loadStageObject("model/weapons/rightHand.json",[0.0,0.0,0.0],0.0,degTo
Radian(2),0.0);
...
}
We changed our
drawScene
function to apply different transformations for
this model. For all other models, we will apply simple translation and rotation
transformations to our ModelView matrix. But in this case, we will simply multiply
the camera matrix to the ModelView matrix to position the arm exactly at the
camera's location and orientation.
function drawScene() {
...
for(var i=0;i<stage.stageObjects.length;++i){
...
if(stage.stageObjects[i].name=="rightHand"){
var mMatrix=mat4.clone(cam.viewMatrix);
mat4.invert(mMatrix,mMatrix);