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.それを使用する
1つのボタンの代わりに、一連のボタン(または、推奨する場合はList<Button>
)を使用してから、ループして、同様の方法ですべてを更新および描画します。
次に、イベントハンドラーでカスタムコードを呼び出すのは簡単です。
void button_OnClick(Button sender)
{
_gameState = GameStates.MainScreen; //or whatever else you might need
}
マウスがホバリングしている場合はテクスチャを変更することを検討したり、スタイリッシュなフェードを使用したりすることもできます。コーディングできれば、可能性は無限大です。