Posts Tagged ‘Extension Methods’

XNA extension methods page

Sunday, January 24th, 2010

Just a short note to let you know that I will gather my extensionmethods on a separate page with sample usage for handy reference.

MouseState ExtensionMethod

Wednesday, January 20th, 2010

Just a little helpermethod to get the mouse's position as a Vector2.

For those of you who still haven't gotten started with extension methods here's a quick writeup'n'sample

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace XNAFAN
{
    public static class MouseStateExtensionMethods
    {

        /// <summary>
        /// Returns the mouseposition as a Vector2
        /// </summary>
        /// <param name="mouse">The current MouseState</param>
        /// <returns>The mouseposition as a Vector2</returns>
        public static Vector2 GetPosition(this MouseState mouse)
        {
            return new Vector2(mouse.X, mouse.Y);
        }
    }
}

This way you don't have to convert x and y every time along the lines of

MouseState mouseState = Mouse.GetState();
Vector2 position = new Vector2(mouseState.X, mouseState.Y);

Instead you just add a reference to the code with the extensionmethod and this enables you to write:

Vector2 position = mouseState.GetPosition();

Nifty - eh...? :-)