c# - 制作按钮 Xna/MonoGame

标签 c# user-interface xna xna-4.0 monogame

我想知道在 MonoGame 中制作按钮的最佳方法是什么。我试图寻找答案,但似乎没有答案。使用 WinForm 按钮是不好的做法吗?如果是这样,存在哪些可行的替代方案?

最佳答案

我一直喜欢制作自定义按钮类,这为我创建创意按钮提供了很大的灵 active 。

该类创建一个带有纹理和位置 x 和位置 y 以及唯一名称的按钮,完成后我将检查我的鼠标位置并查看它是否在按钮内,如果在按钮内按钮然后它可以单击按钮,它将按名称搜索按钮并执行给定的命令:)

这是我的按钮类的一个示例:(不是最好的方法,但是嘿,它对我来说非常有用)

public class Button : GameObject
    {
        int buttonX, buttonY;

        public int ButtonX
        {
            get
            {
                return buttonX;
            }
        }

        public int ButtonY
        {
            get
            {
                return buttonY;
            }
        }

        public Button(string name, Texture2D texture, int buttonX, int buttonY)
        {
            this.Name = name;
            this.Texture = texture;
            this.buttonX = buttonX;
            this.buttonY = buttonY;
        }

        /**
         * @return true: If a player enters the button with mouse
         */
        public bool enterButton()
        {
            if (MouseInput.getMouseX() < buttonX + Texture.Width &&
                    MouseInput.getMouseX() > buttonX &&
                    MouseInput.getMouseY() < buttonY + Texture.Height &&
                    MouseInput.getMouseY() > buttonY)
            {
                return true;
            }
            return false;
        }

        public void Update(GameTime gameTime)
        {
            if (enterButton() && MouseInput.LastMouseState.LeftButton == ButtonState.Released && MouseInput.MouseState.LeftButton == ButtonState.Pressed)
            {
                switch (Name)
                {
                    case "buy_normal_fish": //the name of the button
                        if (Player.Gold >= 10)
                        {
                            ScreenManager.addFriendly("normal_fish", new Vector2(100, 100), 100, -3, 10, 100);
                            Player.Gold -= 10;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        public void Draw()
        {
            Screens.ScreenManager.Sprites.Draw(Texture, new Rectangle((int)ButtonX, (int)ButtonY, Texture.Width, Texture.Height), Color.White);   
        } 
}

关于c# - 制作按钮 Xna/MonoGame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430598/

相关文章:

c# - XNA:获取资源数组/列表?

c# - Google Drive - 如何从代码中清空垃圾(以编程方式)?

c# - 如何从 asp.net 中的可编辑的 div 标签中获取内容?

android - 使用 sherloack bar 为所有应用程序设置背景颜色

python - 如何将和转换为二进制

performance - XNA - 合并 Sprite 以获得更好的绘图性能?

c# - 调用 API 20 次来生成列表,最佳实践?

c# - 不包含定义定义

c++ - mousePressEvent 有效,但 mouseMoveEvent 无效

android - 如何在Android版MonoGame上播放声音效果?