简体   繁体   English

C#Monogame-悬停时更改色彩

[英]C# Monogame - Change tint color on hover

I want to have a class that has the purpose of managing buttons in my game. 我想开设一个旨在管理游戏中按钮的类。 So far I have the following code: 到目前为止,我有以下代码:

public class Button
{
    private SpriteFont btnFont;
    private string btnTxt;
    private Vector2 btnPos;
    private Color btnColour;

    public Button(SpriteFont newFont, string newTxt, Vector2 newPos, Color newColour)
    {
        btnFont = newFont;
        btnPos = newPos;
        btnTxt = newTxt;
        btnColour = newColour;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.DrawString(btnFont, btnTxt, btnPos, btnColour);
    }
}

And the usage: 以及用法:

private Button btn_1;
private Color colour = new Color.CornflowerBlue;
private Rectangle buttonArea_1 = new Rectangle(24, 300, 192, 39);
// LoadContent() Method:
btn_1 = new Button(Game1.defaultFontBig, "Play Game", new Vector2(24, 300), colour);
// Update() Method:
MouseState mouseState = Mouse.GetState();
Point mousePosition = new Point(mouseState.X, mouseState.Y);
if (buttonArea_1.Contains(mousePosition))
{
    colour = Color.Yellow;
    if (mouseState.LeftButton == ButtonState.Pressed)
    {
        Game1.currentGameState = Game1.gameStates.loadingScreen;
    }
}
else
{
    colour = Color.CornflowerBlue;
}
// Draw Method():
btn_1.Draw(spriteBatch);

But something goes wrong... When I test the game and I hover on the button it doesn't change its color from cornflower blue to yellow but still changes the game state as I click on it. 但是出了点问题...当我测试游戏时,当我将鼠标悬停在按钮上时,它的颜色没有从矢车菊蓝色更改为黄色,但是当我单击它时仍然更改了游戏状态。 I feel like this is some kind of simple initialization thing I'm missing so I'm asking for your help. 我觉得这是我缺少的一种简单的初始化操作,因此我需要您的帮助。 Any code examples/approaches explained would be great. 解释的任何代码示例/方法都很棒。

EDIT: 编辑:

Via properties like this? 通过这样的属性?

public Color Colour
{
    public get { return colour; }
    private set { colour = value; }
}

But the does the usage change? 但是用法会改变吗? Can I still pass in the colour to the constructor and change it in Update() ? 我是否仍可以将颜色传递给构造函数并在Update()更改?

Instead of: 代替:

private Color btnColour;

in the button class, do this: 在按钮类中,执行以下操作:

public Color btnColour { get; set; }

then in the usage code, instead of this: 然后在使用代码中,而不是这样:

colour = Color.Yellow;

do this: 做这个:

btn_1.colour = Color.Yellow;

and: 和:

btn_1.colour = Color.CornflowerBlue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM