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 Downloaddownload them as a Windows Game Library with a project that displays some of the methods in use.


MouseState extensionmethods
///

/// Returns the mouseposition as a Vector2
///

/// The current MouseState /// The mouseposition as a Vector2
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
///

/// Gets the center of the Viewport
///

/// The Viewport to get the center of /// The center of the Viewport
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
///

/// Returns the size of the Texture2D as a Vector2
///

/// The texture to get the size of /// The size of the Texture2D as a Vector2
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);