WebGL Textures & Vertices

Beginner's Guide

Page Fifty Two

WebGL Rotations

Rotation Around the Y Axis

Each example, in this book, allows animated rotation around the Y axis. This section demonstrates how to modify entries in a matrix, to enable Y axis rotation. The following graphic illustrates rotating a plane around the Y axis. Assume the user sits where Z labels the Z axis.

Y Rotation

Diagram 16: Y Axis Rotation

Method matrixRotationY(Array, Number), includes two parameters. The first parameter is a JavaScript array of 16 entries, representing a 4 x 4 matrix. The second parameter is a Number representing an angle of rotation, in radians. Method matrixRotationY(Array, Number) returns a JavaScript array representing a 4 x 4 matrix with rotation around the Y axis.

To rotate a default matrix around the Y axis, assign the cosine of the angle to entry 0. Assign the sine of the angle to entry 2. Assign the negative sine of the angle to entry 8 and the cosine of the angle to entry 10. Leave all other array entries unchanged.

The following listing includes the entire matrixRotationY(Array, Number) method. Method matrixRotationY(Array, Number) was modified from code provided under the Apache 2.0 License.

matrixRotationY:  function (m,y){  
var c = Math.cos(y);
var s = Math.sin(y);

return [ 
 c,     m[1],  s,     m[3],
 m[4],  m[5],  m[6],  m[7],
 -s,    m[9],  c,     m[11],
 m[12], m[13], m[14], m[15],

Listing 44: Method matrixRotationY(Array, Number)

To rotate a mesh with matrixRotationY(Array, Number), increment or decrement the number of radians for rotation, per each animation frame. Assign the new radian value to the second parameter of matrixRotationY(Array, Number). Assign a matrix to the first parameter of matrixRotationY(Array, Number).

The default drawing method provided with the book's source code, rotates a mesh for every frame of animation. The method renderDefault(GLControl) from the GLControl class, processes rotation for animation. First obtain the matrix from a GLEntity reference. Second pass the matrix and current rotation as parameters to matrixRotationY(Array, Number). Third increment the rotation. The following listing demonstrates the sequence to obtain a matrix with rotated values. The property, controller.nRad maintains a number representing radians for rotation per animation frame. The controller is a reference to the GLControl class.

matrix = controller.matrixRotationY
controller.nRad += controller.N_RAD;

Listing 45: Generate Y Rotation

See the section titled Animated Rotation for more details regarding how to rotate and animate a WebGL mesh. See the controller's default drawing method renderDefault().

WebGL Beginner's Guide Introduction WebGL Beginner's Guide
Copyright © 2015 Seven Thunder Software. All Rights Reserved.