Drawing Each Ball in Its Current Position

In the draw function, we use a matrix stack to save the state of the Model-View matrix before applying a local transformation for each one of the balls. The code looks like this:

function draw() {
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

transforms.updatePerspective();

try {
gl.uniform1i(program.uUpdateLight, fixedLight);

scene.traverse(object => {
transforms.calculateModelView();
transforms.push();

if (~object.alias.indexOf('ball')) {

const index = parseInt(object.alias.substring(4, 8));
const ballTransform = transforms.modelViewMatrix;
mat4.translate(ballTransform, ballTransform, balls[index].position);
object.diffuse = balls[index].color;
}


transforms.setMatrixUniforms();
transforms.pop();

gl.uniform4fv(program.uMaterialDiffuse, object.diffuse);
gl.uniform4fv(program.uMaterialSpecular, object.specular);
gl.uniform4fv(program.uMaterialAmbient, object.ambient);

gl.uniform1i(program.uWireframe, object.wireframe);
gl.uniform1i(program.uPerVertexColor, object.perVertexColor);

// Bind
gl.bindVertexArray(object.vao);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, object.ibo);

if (object.wireframe) {
gl.drawElements(gl.LINES, object.indices.length, gl.UNSIGNED_SHORT,
0);
}
else {
gl.drawElements(gl.TRIANGLES, object.indices.length,
gl.UNSIGNED_SHORT, 0);
}

// Clean
gl.bindVertexArray(null);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
});
}
catch (error) {
console.error(error);
}
}

The trick here is to use the number that makes up part of the ball alias to look up the respective ball position in the balls array. For example, if the ball being rendered has the ball32 alias, then this code will look for the current position of the ball whose index is 32 in the balls array. This one-to-one correspondence between the ball alias and its location in the ball array was established in the load function.

In the following Time for Action section, we will see the bouncing balls animation in action. We will also discuss some of the code detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.242.141