Saturday, October 25, 2008

XNA Series - Showing the Mouse

Here is a quick one for today. You may have noticed that when using your mouse with XNA that it disappears when entering the game area. This is because XNA wants you to determine what your mouse looks like. If you are programming a game with a mouse or cursor type interface (remember that XBOX 360 and Zune gamers do not have mice!) you probably want a custom mouse cursor. Well, it is really very simple. If we take our basic GameObject class (our custom one we have been using, this is not part of the XNA package) and create a instance lets call it mouseObject.

GameObject mouseObject;
and load it up in LoadContent
mouseObject = new GameObject(Content.Load<Texture2D>("mouse"),
new Rectangle(0,0,25,25));

Then in Update we can update it's position
MouseState ms = Mouse.GetState();
mouseObject.position.X = ms.X;
mouseObject.position.Y = ms.Y;
Then simply call our custom drawing method in Draw

The only other thing that can be helpful here is if your mouse "hotspot" is not in the top left corner, you may want to add an offset value to your gameObject and then in your GameObject.Draw method, do position-offset for the image position. See the attached code sample to see what I did with that (it was an afterthought).

Now you should have your cursor drawn at your mouse's location. You could of course have various cursors in a spritesheet then simply change the source rectangle based on your need.

The source for this post
Post a Comment