上一篇我们讲了自定义游戏鼠标光标,今天我们来讲讲如何在游戏中实现按钮。

首先准备三张图片。

如图:大家可以右键另存为以下三张图片。13   12 10

分别重命名为ButtonNormal.png,ButtonMoveOver.png,ButtonPressed.png,即按钮正常状态图,鼠标移动到按钮上状态图,按钮按下状态图。接着将三张图片复制到【HelloWorld.XNAContent】项目中

image

分别选择这三张图片,右键属性,确保如下三张图的设置,注意Asset Name要和图片名称一致,不带扩展名

image

 

image

image

 

打开Game1.cs文件,找到【Vector2 mouseCursorPosition;】在下方输入定义按钮三种状态的2D纹理图以及按钮的显示的纹理

Texture2D buttonNormal;
Texture2D buttonMoveOver;
Texture2D buttonPressed;
Rectangle buttonRect;
Texture2D button;

接着定义按钮的二维坐标及大小

Rectangle buttonRect;

找到【LoadContent();】方法,在方法体内输入加载图片纹理初始化按钮的三种状态和按钮的二维坐标

buttonNormal = Content.Load<Texture2D>("ButtonNormal");//按钮正常
buttonMoveOver = Content.Load<Texture2D>("ButtonMoveOver");//鼠标悬停到按钮
buttonPressed=Content.Load<Texture2D>("ButtonPressed");//按钮按下

buttonRect = new Rectangle(300, 200,128,128);//按钮坐标位置及大小

由于默认按钮的纹理图是正常状态,所以将buttonNormal赋值给button

button = buttonNormal;

找到【Draw(GameTime gameTime)】方法,在方法体内找到【 spriteBatch.Draw(mouseCursor,mouseCursorPosition,Color.White);】在它的上方输入

spriteBatch.Draw(button, buttonRect, Color.White);

找到【Update(GameTime gameTime)】方法,找到之前鼠标状态代码,替换为

MouseState mouseState = Mouse.GetState();//获取鼠标状态
            if(mouseState.LeftButton==ButtonState.Pressed)//判断是否按下了鼠标左键
            {
                backgoundColor = Color.Red;//将背景设置为红色
                if (buttonRect.Contains(mouseState.X, mouseState.Y))//判断鼠标是否移动到按钮上并且按下
                {
                    button = buttonPressed;//将按钮设置为按下状态
                }
            }
            else 
            {
                if (buttonRect.Contains(mouseState.X, mouseState.Y))//判断鼠标是否移动到按钮上
                {
                    button = buttonMoveOver;//将按钮设置为悬停状态
                }
                else//鼠标不在按钮上
                {
                    button = buttonNormal;//将按钮设置为正常状态
                }
                backgoundColor = Color.CornflowerBlue;//放开鼠标左键恢复成蓝色 
            }

完整代码如下:

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;

        Texture2D buttonNormal;
        Texture2D buttonMoveOver;
        Texture2D buttonPressed;
        Rectangle buttonRect;
        Texture2D button;

        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");

            buttonNormal = Content.Load<Texture2D>("ButtonNormal");
            buttonMoveOver = Content.Load<Texture2D>("ButtonMoveOver");
            buttonPressed=Content.Load<Texture2D>("ButtonPressed");

            buttonRect = new Rectangle(300, 200,128,128);

            button = buttonNormal;
        }

        /// <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;//将背景设置为红色
                if (buttonRect.Contains(mouseState.X, mouseState.Y))//判断鼠标是否移动到按钮上并且按下
                {
                    button = buttonPressed;//将按钮设置为按下状态
                }
            }
            else 
            {
                if (buttonRect.Contains(mouseState.X, mouseState.Y))//判断鼠标是否移动到按钮上
                {
                    button = buttonMoveOver;//将按钮设置为悬停状态
                }
                else//鼠标不在按钮上
                {
                    button = buttonNormal;//将按钮设置为正常状态
                }
                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(button, buttonRect, Color.White);
    

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

            base.Draw(gameTime);
        }
    }
}

点击【启动】

image

运行效果如图: