Drawing Multiple Triangles
I won't spend much time and space talking about drawing multiple primitives. In this case, triangles. Our current code is already easy to expand to drawing multiple shapes. I'll only briefly show it here. This step is necessary so we can move forward to creating more advanced examples in the future tutorials.
Please head over to hello triangle and vertex colored triangle tutorials to see how the rest of this process works. On this page, only vertex data is provided, the shaders are explained in those other tutorials.
// Specify triangle vertex data: var vertices = new Float32Array([ // Triangle 1 vertices: 0.0, 0.5, 0.0, // Vertex A (x,y,z) -0.5, -0.5, 0.0, // Vertex B (x,y,z) 0.5, -0.5, 0.0, // Vertex C (x,y,z) // Triangle 2 vertices: 0.05 + 0.0, 0.75, 0.0, // Vertex A (x,y,z) 0.75 - 0.5, -0.75, 0.0, // Vertex B (x,y,z) 0.15 + 0.5, -0.75, 0.0, // Vertex C (x,y,z) ]); var colors = new Float32Array([ // Triangle 1 vertex colors: 1.0, 0.0, 0.0, // Vertex A (r,g,b) -- red 0.0, 1.0, 0.0, // Vertex B (r,g,b) -- green 0.0, 0.0, 1.0, // Vertex C (r,g,b) -- blue // Triangle 2 vertex colors: 0.0, 0.0, 1.0, // Vertex A (r,g,b) -- red 0.0, 1.0, 0.0, // Vertex B (r,g,b) -- green 1.0, 0.0, 0.0 // Vertex C (r,g,b) -- blue ]);
Simply continue adding new values to each attribute array. The next set of vertices in vertices array will define location of the second triangle. Likewise, the colors array is also extended to provide vertex colors for it.
Finally, there is one more thing to do. We now have to let the indices array know that we have new data. Simply add new indices in consequent order:
var indices = [0, 1, 2, 3, 4, 5];
When drawElements function is executed, it automatically calculates the length of our indices array as demonstrated below. This way there are on changes to be made here. indices.length will automatically pass the number of vertices that will be associated with this new set of data.
// Draw triangle gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
And I think we're ready to go!
This example produces two triangles as shown on the screenshot below:
Note that the vertex colors are also switched around on the second triangle.
This lesson was important. Because we can now take these principles and load an entire game world into our engine from an OBJ or PLY file.