Best way to draw a primitive on the screen is declare an array of vertices and pass those to the DrawUserPrimitive method. Now lets see how to do it. First you need to create an instance of BasicEffect.
Create a new xna game project. Then define the following variables in your class.
VertexPositionColor[] userPrimitives;
BasicEffect basicEffect;
Define the vertices and create a new instance of BasicEffect. Add the following code in your LoadContent method.
//Create the vertices for traingle
userPrimitives = new VertexPositionColor[3];
userPrimitives[0] = new VertexPositionColor();
userPrimitives[0].Position = new Vector3(0, 1, 0);
userPrimitives[0].Color = Color.Green;
userPrimitives[1] = new VertexPositionColor();
userPrimitives[1].Position = new Vector3(1, -1, 0);
userPrimitives[1].Color = Color.Red;
userPrimitives[2] = new VertexPositionColor();
userPrimitives[2].Position = new Vector3(-1, -1, 0);
userPrimitives[2].Color = Color.Yellow;
//Create new basic effect and properties
basicEffect = new BasicEffect(GraphicsDevice);
basicEffect.World = Matrix.Identity;
basicEffect.View = Matrix.CreateLookAt(new Vector3(0, 0, 3), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 100.0f);
basicEffect.VertexColorEnabled = true;
Now you have to implement the Draw method. Add the following code to Draw method.
//Start using the BasicEffect
basicEffect.CurrentTechnique.Passes[0].Apply();
//Draw the primitives
GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, userPrimitives, 0, 1);
Build and run the project. Now your render will look like this.
Also you can draw multiple primitives using the LineStrip primitive. Update the vertices definition section.
userPrimitives = new VertexPositionColor[4];
userPrimitives[0] = new VertexPositionColor();
userPrimitives[0].Position = new Vector3(-1, 1, 0);
userPrimitives[0].Color = Color.Blue;
userPrimitives[1] = new VertexPositionColor();
userPrimitives[1].Position = new Vector3(-1, -1, 0);
userPrimitives[1].Color = Color.Yellow;
userPrimitives[2] = new VertexPositionColor();
userPrimitives[2].Position = new Vector3(1, 1, 0);
userPrimitives[2].Color = Color.Green;
userPrimitives[3] = new VertexPositionColor();
userPrimitives[3].Position = new Vector3(1, -1, 0);
userPrimitives[3].Color = Color.Red;
Update the draw method.
GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineStrip, userPrimitives, 0, 3);
Now your render will look like this.
No comments:
Post a Comment