1.创建一个Button类
你如何添加这样简单的东西:
public delegate void ButtonEvent(Button sender);
public class Button
{
public Vector2 Position { get; set; }
public int Width
{
get
{
return _texture.Width;
}
}
public int Height
{
get
{
return _texture.Height;
}
}
public bool IsMouseOver { get; private set; }
public event ButtonEvent OnClick;
public event ButtonEvent OnMouseEnter;
public event ButtonEvent OnMouseLeave;
Texture2D _texture;
MouseState _previousState;
public Button(Texture2D texture, Vector2 position)
{
_texture = texture;
this.Position = position;
_previousState = Mouse.GetState();
}
public Button(Texture2D texture) : this(texture, Vector2.Zero) { }
public void Update(MouseState mouseState)
{
Rectangle buttonRect = new Rectangle((int)this.Position.X, (int)this.Position.Y, this.Width, this.Height);
Point mousePoint = new Point(mouseState.X, mouseState.Y);
Point previousPoint = new Point(_previousState.X, _previousState.Y);
this.IsMouseOver = false;
if (buttonRect.Contains(mousePoint))
{
this.IsMouseOver = true;
if (!buttonRect.Contains(previousPoint))
if (OnMouseEnter != null)
OnMouseEnter(this);
if (_previousState.LeftButton == ButtonState.Released && mouseState.LeftButton == ButtonState.Pressed)
if (OnClick != null)
OnClick(this);
}
else if (buttonRect.Contains(previousPoint))
{
if (OnMouseLeave != null)
OnMouseLeave(this);
}
_previousState = mouseState;
}
public void Draw(SpriteBatch spriteBatch)
{
//spritebatch has to be started! (.Begin() already called)
spriteBatch.Draw(_texture, Position, Color.White);
}
}
2. 设置
要使用它,您需要在某处提供参考
Button _button;
在你的LoadContent
,你可能会做类似的事情
button = new Button(Content.Load<Texture2D>("Textures\\Button"), new Vector2(100, 100));
button.OnClick += new ButtonEvent(button_OnClick);
button.OnMouseEnter += new ButtonEvent(button_OnMouseEnter);
button.OnMouseLeave += new ButtonEvent(button_OnMouseLeave);
在Update
你打电话
button.Update(Mouse.GetState());
在Draw
你打电话
spriteBatch.Begin();
button.Draw(spriteBatch);
spriteBatch.End();
3.使用它
代替一个按钮,使用一组按钮(或者,如果我可以推荐的话,一个List<Button>
),然后循环更新并以类似的方式绘制它们。
然后很容易在事件处理程序上调用自定义代码:
void button_OnClick(Button sender)
{
_gameState = GameStates.MainScreen; //or whatever else you might need
}
如果鼠标悬停,您甚至可以考虑更改纹理,或者使用时尚的淡入淡出 - 如果您可以编码,可能性是无穷无尽的!