Getting started with XNA – Primitives: the basics part 2

In this tutorial, we’ll need the source from the previous one. In this tutorial, we’ll draw a triangle again, but this time with a TriangleList instead of a LineList.
When we draw a triangle using a LineList, we have to define 6 vertices, which is a lot for a triangle. When we use a TriangleList, we only need to define 3 vertices, one for each corner.

We’ll start by opening our previous project, and copying the TriangleLineList class. Rename the copied class to TriangleTriangleList.

Replace the vertex declaration by the following code:
// an array of the vertices that have to be drawn
VertexPositionColor[] vertices = new VertexPositionColor[3];

We do this because with a TriangleList, we only need 3 vertices.
Then we change our vertices:
// create our triangle by setting up the vertices.
// because we use a triangle list as primitive type, we only need 3 vertices
vertices[0].Position = new Vector3(250, 100, 0);
vertices[0].Color = Color.Red;

vertices[1].Position = new Vector3(350, 200, 0);
vertices[1].Color = Color.Red;

vertices[2].Position = new Vector3(250, 200, 0);
vertices[2].Color = Color.Red;

Notice that we’ve declared the vertices in a clockwise order!

Then in the drawing code, update the following line of code:
// draw the vertices as a triangle list.
GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1);

First off all, we changed the Primitive Type to TriangleList. Second of all, we’ve changed the primitive Count parameter to 1, because we don’t need to draw 3 lines, but 1 triangle.

Last but not least, add this line to the Initialize method of your game class:
this.Components.Add(new TriangleTriangleList(this));

Press F5 and you’ll now see 2 triangles.
Our second triangle

Now we draw our triangle more optimized. In the next tutorial, we’ll draw a square and introduce the concept of an index buffer.

You can download the source code here.