Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Rectangle in MonoGame

How do you draw shapes, such as Rectangles and Circles, in MonoGame without having to save the a predrawn shape in the Content folder?

DrawRectangle() and DrawEllipse() are for Windows Form and do not work in OpenGL, which is what I am using.

like image 637
Evorlor Avatar asked Apr 26 '14 01:04

Evorlor


People also ask

What is source rectangle XNA?

The source rectangle defines the area of the texture that will be displayed. So if you have a 40x40 texture, and your rectangle is (0, 0, 20, 20), only the top left corner of the texture will be displayed. If you specify null for the rectangle, you will draw the entire texture.


1 Answers

Use 3D primitives and a 2D projection

Here's a simple example with explanations

I define a 10x10 rectangle and set the world matrix to make it look like a 2D projection :

Note : the BasicEffect is what draws your primitive

protected override void LoadContent()
{
    _vertexPositionColors = new[]
    {
        new VertexPositionColor(new Vector3(0, 0, 1), Color.White),
        new VertexPositionColor(new Vector3(10, 0, 1), Color.White),
        new VertexPositionColor(new Vector3(10, 10, 1), Color.White),
        new VertexPositionColor(new Vector3(0, 10, 1), Color.White)
    };
    _basicEffect = new BasicEffect(GraphicsDevice);
    _basicEffect.World = Matrix.CreateOrthographicOffCenter(
        0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
}

Then I draw the whole thing :D

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    EffectTechnique effectTechnique = _basicEffect.Techniques[0];
    EffectPassCollection effectPassCollection = effectTechnique.Passes;
    foreach (EffectPass pass in effectPassCollection)
    {
        pass.Apply();
        GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineStrip, _vertexPositionColors, 0, 4);
    }
    base.Draw(gameTime);
}

There you have your rectangle !

enter image description here

Now this is just the tip the of the iceberg,

  • To draw filled rectangles : draw 2 triangle primitives
  • For an ellipse/circle see these : Draw an Ellipse in XNA and Draw simple circle in XNA

Or as mentioned in one of the posts above you could use a shader that does it instead ...

I needed to draw a Superellipse a while ago and ended up sketching this shader :

Drawing a SuperEllipse in HLSL

As you can see in the post a Superellipse not only draws ellipse but also other shapes and maybe even circles (I did not test) so you might be interested in it.

Ultimately you will want some class/methods to hide all these details so you just have to invoke something like DrawCircle().

Tip : by posting @ https://gamedev.stackexchange.com/ you will likely get more answers for Monogame-related questions

:D

like image 143
aybe Avatar answered Sep 30 '22 13:09

aybe