我希望有一个课程,其目的是管理游戏中的按钮。到目前为止,我有以下代码:
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);
}
}
用法:
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);
但是出了点问题...当我测试游戏并且我将鼠标悬停在按钮上时,它的颜色不会从矢车菊蓝色变为黄色,但是当我点击它时仍会改变游戏状态。我觉得这是一种我想念的简单初始化的东西,所以我在寻求你的帮助。解释的任何代码示例/方法都会很棒。
修改
通过这样的属性?
public Color Colour
{
public get { return colour; }
private set { colour = value; }
}
但是用法会改变吗?我仍然可以将颜色传递给构造函数并在Update()
中更改它吗?
答案 0 :(得分:0)
而不是:
private Color btnColour;
,执行以下操作:
public Color btnColour { get; set; }
然后在使用代码中,而不是:
colour = Color.Yellow;
这样做:
btn_1.colour = Color.Yellow;
和
btn_1.colour = Color.CornflowerBlue;