How to use Mouse in XNA

In this mini-article, I will show you how you can make use most of Mouse object.

In this mini-article, I will show you how you can make use most of Mouse object.

How to make Mouse Visible?

If you want to see default mouse,just add these codes anywhere on your code:

this.IsMouseVisible = true; 

How to make a custom Cursor?

The trick is to add a texture that look like a mouse cursor and set its x and y values to the mouse's state.

Variable Declarations

Texture2D myTexture;
Vector2 spritePosition = Vector2.Zero;

LoadContent Function

myTexture = Content.Load<Texture2D>("cursor//nicecursor");

Update Function

spritePosition.X = Mouse.GetState().X;

spritePosition.Y = Mouse.GetState().Y;

Draw Function

spriteBatch.Draw(myTexture, new Rectangle((int)spritePosition.X, (int)spritePosition.Y, 24, 24), Color.White);
 

The texture will move as Mouse moves.

How to make a custom animated-Cursor?

Its similar to static cursor with more textures displaying like an animation.

Variable Declarations

Texture2D myTexture;      

Vector2 spritePosition = Vector2.Zero;    

private int a;   


LoadContent Function

myTexture = Content.Load<Texture2D>("cursor//11a_1"); 

Update Function

spritePosition.X = Mouse.GetState().X;
spritePosition.Y = Mouse.GetState().Y;
a++;
if (a == 24)
{
    a = 1;
}
else
{
    myTexture = Content.Load<Texture2D>("cursor//11a_" + a);
}    

Draw Function

spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
spriteBatch.Draw(myTexture, new Rectangle((int)spritePosition.X, (int)spritePosition.Y, 24, 24), Color.White);
spriteBatch.End();

Using these codes you will be able to see an animated cursor!

Hope you liked the article! 

Cheers