Tuesday, December 22, 2009

A very small Chirstmas present from Botworks

Well seeming as I haven't finished any of the projects I am working on yet (more on what they are in the new year) so I can't offer discounts or bonus content. However, I can offer a little something for XNA developers. One of the things that I found most frustrating in XNA was drawing a line, so I created a little function to do just that. It isn't especially clever, but it gets the job done

void drawLine(Texture2D line,int lineWidth,Vector2 startPosition,Vector2 endPosition,SpriteBatch spriteBatch)
{
float length = Vector2.Distance(startPosition, endPosition);
float theta = (float)Math.Atan((double)((endPosition.X - startPosition.X) / (endPosition.Y - startPosition.Y)));
float alpha = (float)(2*Math.PI) - theta;
spriteBatch.Begin();
spriteBatch.Draw(line, new Rectangle((int)startPosition.X, (int)startPosition.Y, lineWidth, (int)length), null, Color.White, alpha, new Vector2(lineWidth/2,0), SpriteEffects.None, 0);
spriteBatch.End();
}
  • line - this a pre-loaded texture2D which is your basic line pixel. It needs to be 1 pixel high. It can be of any width (for example if you want a glowing line) but a standard line is 1 pixel wide
  • lineWidth - unsurprisingly this is the width of the texture loaded in the line property
  • startPosition, endPosition - these vectors are the start and end co-ordinates of the line
  • spriteBatch - this is just the instance of the spriteBatch which, unless you have specifically changed, is just called spriteBatch



And here is a quick demonstration. I am using a 21x1 image file which is just a red pixel in the middle with fading transparencies going out to create something of a laser effect.

Merry Christmas and a happy and productive new year to you all.

No comments: