Drawing Lines in XNA

One of the things I realized is very handy when prototyping or debugging is to draw a line on a specific location. Like drawing lines around collision boxes to see if your character is making a proper collision. For my games I’ve made a small LineBatch.
Basically LineBatch uses a SpriteBatch to draw the lines by stretching a 1×1 white Texture2D to your line size.
You can give it 2 points ( start and end point of course) and a color. There’s an overload function that receives the Layer parameter.

LineBatch::DrawLine(SpriteBatch batch, Color color, Vector2 point1, Vector2 point2);
LineBatch::DrawLine(SpriteBatch batch, Color color, Vector2 point1, Vector2 point2, float Layer);

LineBatch is a static class, you only need to call LineBatch::Init(GraphicsDevice) somewhere on your code.
Then use you can use like this:

LineBatch.DrawLine(_spriteBatch,
                          Color.Black,
                          Vector2.Zero,
                          new Vector2(100,300));

I’ve made a small unit test that you can download here. Try clicking the screen to set a start and end point.

Here’s a video showing the result:

More Reading

Post navigation

  • Hey David,

    First of all, thanks for your handy class. I just want to let you know that a lot of XNA 4.0 will be reading this in the future (if not now) and you should warn them to change their Init method code to:

    _empty_texture = new Texture2D(device, 1, 1, false, SurfaceFormat.Color);

    because TextureUsage doesn’t exist anymore.

    Cheers!

  • Here my contribution:
    The code draws a 1px line. For more weight lines, you will need, first change this code on Init method:
    _empty_texture = new Texture2D(device, 3, 3, false, SurfaceFormat.Color);

    After that, you will complete colors data as matrix that you fill before. In my exemple, i use 3×3

    //Check if data has been set for texture
    //Do this only once otherwise
    if (!_set_data)
    {
    _empty_texture.SetData(new[] { Color.White, Color.White, Color.White,
    Color.White, Color.White, Color.White,
    Color.White, Color.White, Color.White });
    _set_data = true;
    }

    Thit is very simple to experient guys, but, help who are starting your code carreer =)

Leave a Reply

Your email address will not be published. Required fields are marked *