首页 > Computer > XNA > XNA Series – Showing the Mouse
2009
02-17

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("mouse"),
0,0,
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

mouseObject.Draw(spriteBatch);

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

最后编辑:
作者:wy182000
这个作者貌似有点懒,什么都没有留下。

留下一个回复