HTML and CSS Reference
In-Depth Information
Finally, here is one for rotation on the z-axis:
cos sin 0
-sin cos 0
0 0 1
It's good practice to go ahead and multiply each of these by an x, y, z matrix and verify that you get the
same formulas you used for coordinate rotation on those two axes in Chapter 15.
Coding with matrices
Now you know enough of the basics to start programming with matrices. We're going to reuse and alter
the 13-rotate-xy.html example from Chapter 15, so open that up. That exercise had a rotateX and
rotateY function to perform the 3D coordinate rotation. We will change these so they work with matrices.
Start with the rotateX function. The updated code takes the ball's x, y, z coordinates, puts them in a 1 × 3
matrix, and then creates an x rotation matrix based on the given angle. These matrices are in the form of
arrays. It then multiplies these two matrices together using the matrixMultiply function, which you also
need to create. The result of the multiplication is another array, so you have to assign those values back to
the ball's x, y, and z coordinates. Here's the new version of the rotateX function:
function rotateX (ball, angle) {
var position = [ball.xpos, ball.ypos, ball.zpos],
sin = Math.sin(angle),
cos = Math.cos(angle),
xRotMatrix = [];
xRotMatrix[0] = [1, 0, 0];
xRotMatrix[1] = [0, cos, sin];
xRotMatrix[2] = [0, -sin, cos];
var result = matrixMultiply(position, xRotMatrix);
ball.xpos = result[0];
ball.ypos = result[1];
ball.zpos = result[2];
}
And here is the function used for matrix multiplication:
function matrixMultiply (matrixA, matrixB) {
var result = [];
result[0] = matrixA[0] * matrixB[0][0] +
matrixA[1] * matrixB[1][0] +
matrixA[2] * matrixB[2][0];
result[1] = matrixA[0] * matrixB[0][1] +
matrixA[1] * matrixB[1][1] +
matrixA[2] * matrixB[2][1];
result[2] = matrixA[0] * matrixB[0][2] +
matrixA[1] * matrixB[1][2] +
matrixA[2] * matrixB[2][2];
return result;
}
 
Search WWH ::




Custom Search