/* * * * * * * * * * * * * * * * * * * * * * * * * * * Renders 2D primitives (lines) specified in screen/pixel space * using an instance of BasicEffect. * * By Karn Bianco - www.KarnBianco.co.uk * * * * * * * * * * * * * * * * * * * * * * * * * * */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace NamespaceGoesHere { public class Render2DLines : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; Vector2[] vertices; // Vertices defined in screen space VertexPositionColor[] verticesForGPU; // 3D vertices required for rendering int[] indices; // Indices for defining lines from points BasicEffect basicEffect; // BasicEffect instance public Render2DLines() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.graphics.PreferredBackBufferWidth = 450; this.graphics.PreferredBackBufferHeight = 300; } protected override void LoadContent() { // Create a new instance of BasicEffect basicEffect = new BasicEffect(GraphicsDevice, null); // Set up vertices in screen space (just as you would set sprite positions) vertices = new Vector2[4]; vertices[0] = new Vector2(10, 10); vertices[1] = new Vector2(400, 10); vertices[2] = new Vector2(400, 150); vertices[3] = new Vector2(10, 150); // Set up 3D vertices using screen space vectors and a 0 component for z-value verticesForGPU = new VertexPositionColor[4]; for (int i = 0; i < vertices.Length; i++) { verticesForGPU[i].Position = new Vector3( vertices[i].X / GraphicsDevice.PresentationParameters.BackBufferWidth * 2.0f - 1.0f, vertices[i].Y / GraphicsDevice.PresentationParameters.BackBufferHeight * -2.0f + 1.0f, 0); verticesForGPU[i].Color = Color.White; } // Generate two indices for each vertex indices = new int[8] { 0, 1, 1, 2, 2, 3, 3, 0 }; // Set vertex declaration GraphicsDevice.VertexDeclaration = new VertexDeclaration( GraphicsDevice, VertexPositionColor.VertexElements); } protected override void Update(GameTime gameTime) { base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // Renders lines using color component of VertexPositionColor basicEffect.VertexColorEnabled = true; basicEffect.Begin(); basicEffect.CurrentTechnique.Passes[0].Begin(); GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.LineList, verticesForGPU, 0, verticesForGPU.Length, indices, 0, indices.Length / 2); // Draw lines basicEffect.CurrentTechnique.Passes[0].End(); basicEffect.End(); base.Draw(gameTime); } } }