How to create a View matrix in Javascript.
First let's modify drawScene() to use a view matrix function to return our view matrix:
Assignment 2 drawScene() code
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);
mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [0.0, 0.0, -5.0]);
mat4.rotate(mvMatrix, xRot/180.0*3.1415, [0, 0, 0]);
mat4.rotate(mvMatrix, yRot/180.0*3.1415, [0, 1, 0]);
mat4.rotate(mvMatrix, zRot/180.0*3.1415, [0, 0, 0]);
......
The mat4.translate and mat4.rotate calls are doing the basic View transformation in A2. Now we replace this code with the following:
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);
mat4.identity(mvMatrix);
// call a function to generate the view matrix for the Tank Camera
aviewmatrix = genViewMatrix();
// now fold the view matrix into the Model View Matrix
mat4.multiply(mvMatrix, aviewmatrix);
......
Now let's write the code for creating the view matrix
// this function creates a view matrix using the javascript mat4 library.
// the mat4.lookAt function is used which calculates the Model Space
// to View space transformation matrix
function genViewMatrix()
{
// the lookAt function requires three parameters:
// an eyepos - this is a vec3 variable where the camera is in world coords.
// a target - this is the point your camera is looking at.
// an Up vector - this specifies the direction for the top of your camera
eyepos = [0.0, 0.4, 0.0]; // camera slight above the origin.
target = [0.0, 0.4, -1.0]; // Camera looking straight down Z axis
up = [0.0, 1.0, 0.0]; // the UP vector for the camera is simply straight up.
aviewmatrix = mat4.lookAt(eyepos,target,up);
return aviewmatrix;
}
Implementing this code will give you a camera just above the origin looking in the -z direction into the scene.
So how do I modify this to implement Assignment 3?
- Have your mouse handler modify the eyepos variable to move the tank around. You would make eyepos a global variable and have the mouse handler just change the eyepos variable.
vec3.scale(viewdirection,Speed, scaledir); // multiply speed time view direction to give a scaled view direction vec3.add(eyepos,scaledir,eyepos); // add speed adjusted direction to eyepos
- Have your mouse handler change a view direction vector and then compute the target by adding the view direction vector to the eye position:
vec3.add(eyepos,viewdirection,target);