XNA Extension Methods
Here I am going to gather the extensionmethods I come up with during my XNA coding.
There are probably other coders out there who have come up with similar code, but usually when I get the idea it's faster to just write the method than to go Googling :).
There are other sites out there with extensionmethods for XNA - XNAWiki is one of them.
Nick Gravelyn has a collection of extension methods on Codeplex for download as well.
I also add my extensionmethods to the XNAWiki, but I also like to add some comments and sample usage, which I can do here.
You can download them as a Windows Game Library with a project that displays some of the methods in use.
MouseState extensionmethods
///
///
///
The current MouseState
///
public static Vector2 GetPosition(this MouseState mouse)
{
return new Vector2(mouse.X, mouse.Y);
}
Sample usage 1:
//displays the mouse's position on screen
spriteBatch.DrawString(defaultFont,
"Mouseposition: " + mouseState.GetPosition(),
mouseState.GetPosition(), Color.White);
Sample usage 2:
//displays a custom mousecursor (here a Texture2D)
spriteBatch.Draw(txt2DcustomCursor,
mouseState.GetPosition(),
Color.White);
Viewport extensionmethods
///
///
///
The Viewport to get the center of
///
public static Vector2 GetCenter(this Viewport viewPort)
{
return new Vector2(viewPort.Width / 2, viewPort.Height / 2);
}
Sample usage 1:
//centers a string onscreen
string strCenter = "CENTER";
Vector2 textSize = defaultFont.MeasureString(strCenter);
spriteBatch.DrawString(defaultFont, //font to use
strCenter, //what to write
graphics.GraphicsDevice.Viewport.GetCenter() - textSize / 2,
Color.White);
Texture2D extensionmethods
///
///
///
The texture to get the size of
///
public static Vector2 GetSize(this Texture2D texture)
{
return new Vector2(texture.Width, texture.Height);
}
Sample usage 1:
//Centers a Texture2D on screen
spriteBatch.Draw(texture,
graphics.GraphicsDevice.Viewport.GetCenter() - texture.GetSize() / 2,
Color.White);