26
Jan
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:


January 26th, 2010 at 11:33
[...] This post was mentioned on Twitter by Glenn Wilson, David Amador. David Amador said: New Blog Post: Drawing Lines in XNA http://www.david-amador.com/2010/01/drawing-lines-in-xna/ [...]
June 22nd, 2010 at 19:21
Wow thats great thanks love your blog.
November 2nd, 2010 at 11:45
It’s just absurd that they didn’t include basic line drawing functionality. Way to go Microsoft!
April 11th, 2011 at 1:10
[...] draw the polygon’s outline by using a DrawLine(from, to) function such as the one described here. Before I discovered this trick, I’d loop through each vertex in the list and draw a line [...]
April 15th, 2011 at 3:57
How would this be converted to use points in 3D space?
July 16th, 2011 at 22:56
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!