上一篇我们讲了在游戏中使用系统默认鼠标,这一篇我们来讲讲如何在游戏中使用自定义鼠标。

首先我们需要一张透明背景的png图片,鼠标箭头指向左上角顶点位置。尺寸大小为32×32像素。

如图:MouseCursor 各位可以右键图片另存为并重命名为MouseCursor.png。然后将该png图片拷贝到【HelloWorld.XNAContent】项目中。选中MouseCursor.png右键属性,将图片的AssetName改为MouseCursor。Content Importer为Texture-XNA Framework,Content Processor为Texture-XNA Framework (默认无需修改)

 

image

 

打开Game1.cs文件,找到【Color backgoundColor;】在它下面定义一个鼠标的2D纹理和一个鼠标位置

Texture2D mouseCursor;
Vector2 mouseCursorPosition;

找到【Game1()】构造方法,在方法体内将【IsMouseVisible = true;】改为【IsMouseVisible = false;】

IsMouseVisible = false;

找到【LoadContent()】方法,在方法体内加入

mouseCursor = Content.Load<Texture2D>("MouseCursor");

加载鼠标纹理文件,【“MouseCursor”】就是前面定义的Asset Name

找到【Update(GameTime gameTime)】方法,由于前面已经定义了鼠标状态,只需要加入

mouseCursorPosition = new Vector2(mouseState.X, mouseState.Y);

定义鼠标移动的位置,Vector2是一个二维坐标。游戏界面左上角顶点为0,0,向右是x轴递增,向下是y轴递增。mouseState.X和mouseState.Y就是鼠标移动到游戏界面中的坐标。

最后找到【Draw(GameTime gameTime)】方法,在【spriteBatch.End();】前面输入

spriteBatch.Draw(mouseCursor,mouseCursorPosition,Color.White);

由于spriteBatch.Begin存在层次关系,后画会覆盖前画,鼠标必须在最顶层,所以要放在最后即【spriteBatch.End();】前一行。spriteBatch.Draw的第一个参数是鼠标二维纹理图,第二个参数表示鼠标位置,第三个参数可以认为将白色不绘制。

完整代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace HelloWorld.XNA
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont defaultFont;
        Color backgoundColor;
        Texture2D mouseCursor;
        Vector2 mouseCursorPosition;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 600;
            graphics.IsFullScreen = false;
            IsMouseVisible = false;//使用自定义鼠标,关闭系统默认鼠标
        }
        

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            defaultFont = Content.Load<SpriteFont>("DefaultFont");

            backgoundColor = Color.CornflowerBlue;

            mouseCursor = Content.Load<Texture2D>("MouseCursor");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            KeyboardState keyboardState = Keyboard.GetState(PlayerIndex.One);
            if(keyboardState.IsKeyDown(Keys.Escape))
            {
                this.Exit();
            }
            if(keyboardState.IsKeyDown(Keys.F10))
            {
                graphics.IsFullScreen = true;
                graphics.ApplyChanges();
            }
            if(keyboardState.IsKeyDown(Keys.F11))
            {
                graphics.IsFullScreen = false;
                graphics.ApplyChanges();
            }
            if (keyboardState.IsKeyDown(Keys.F12))
            {
                graphics.PreferredBackBufferWidth = 1920;
                graphics.PreferredBackBufferHeight = 1080;
                graphics.ApplyChanges();
            }

            MouseState mouseState = Mouse.GetState();//获取鼠标状态
            if(mouseState.LeftButton==ButtonState.Pressed)//判断是否按下了鼠标左键
            {
                backgoundColor = Color.Red;//将背景设置为红色
            }
            else 
            {
                backgoundColor = Color.CornflowerBlue;//放开鼠标左键恢复成蓝色
            }

            mouseCursorPosition = new Vector2(mouseState.X, mouseState.Y);//设置自定义鼠标的位置为鼠标移动位置

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(backgoundColor);//绘制游戏背景

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            spriteBatch.DrawString(defaultFont, "这是我的第一个游戏", Vector2.Zero, Color.White);
            spriteBatch.Draw(mouseCursor,mouseCursorPosition,Color.White);//绘制自定义鼠标
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

 

 

点击【启动】

image

运行效果: