Sunday, March 2, 2008

Displaying a Mouse Pointer in XNA

XNA doesn't automatically show you a mouse pointer within the game window. Solving this is easy. First, you need a position for your mouse. You'll also need a 2d texture to display as your mouse pointer. Declare this within your game class:


Texture2D m_mouseTexture;

Vector2 m_mousePos;



Be sure to initialize it to zero. For simplicity, I also generate a simple red square texture to use as the mouse pointer. I'm doing all of this in the Initialize() function. In my (very short) experience with XNA, you'd want to initialize textures in the LoadContent() function, but this is not loading from a file, so it's safe to do it all in the Initialize() function like this:


m_mousePos = Vector2.Zero;

 

m_mouseTexture = new Texture2D(graphics.GraphicsDevice, (int)POINTSIZE, (int)POINTSIZE, 1, TextureUsage.None, SurfaceFormat.Color);

 

Color[] texture = new Color[POINTSIZE * POINTSIZE];

for (int i = 0; i < texture.Length; ++i)

{

    texture[i] = Color.Red;

}

m_mouseTexture.SetData(texture);



Now, in the Update() function, update your mouse position:


MouseState mouseState = Mouse.GetState();

m_mousePos.X = mouseState.X;

m_mousePos.Y = mouseState.Y;



And finally, in the Draw() function, draw your sprite in a spritebatch:


spriteBatch.Begin();

spriteBatch.Draw(m_mouseTexture, m_mousePos, null, Color.White, 0f,

        Vector2.Zero, 1.0f, SpriteEffects.None, 0f);

spriteBatch.End();



Grab the sample project for this here.

No comments: