Drawing a rectangle on monogame

I’ve been trying to get some information about drawing a single rectangle on monogame to no avail, too much information scattered and unfinished examples (and a lot of obfuscated exceptions on code).

First we need the starting position (I used the location where the user pressed and maintains pressed the left click):

_selectionInitialPosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); // it’s set just once on left click press
Vector2 mousePosition = Extensions.GetMouseVector2(); // Current position, refreshes in every update call

Now we set the vertex points:

var vertexPositionColors = new[]
 new VertexPositionColor(
 new Vector3(_selectionInitialPosition.X, _selectionInitialPosition.Y, 0), Color.White),
 new VertexPositionColor(new Vector3(_selectionInitialPosition.X, mousePosition.Y, 0), Color.White),
 new VertexPositionColor(new Vector3(mousePosition.X, _selectionInitialPosition.Y, 0), Color.White),
 new VertexPositionColor(new Vector3(mousePosition.X, mousePosition.Y, 0), Color.White)

Then we get the “draw pattern” (From a to b, from b to c, etc):

var lineStripIndices = new short[] {0, 2, 3, 1, 0};

And heres the drawing part:

var basicEffect = new BasicEffect(graphicsDevice) // Used for drawing
 View = Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 1.0f), Vector3.Zero, Vector3.Up), // camera
 Projection = Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width,
 graphicsDevice.Viewport.Height,0, 1.0f, 1000.0f) // Offset position
 PrimitiveType.LineStrip, vertexPositionColors,
 0, // vertex buffer offset to add to each element of the index buffer
 4, // number of vertices to draw
 0, // first index element to read
 4 // number of primitives to draw 

Here’s the result (white rectangle):



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s