using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Tutorial030.Controls { public class Button : Component { protected MouseState _previousMouse; protected MouseState _currentMouse; protected Texture2D _texture; protected SpriteFont _font; protected Color _colour; public Vector2 Position; public Rectangle Rectangle { get { return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height); } } public Color PenColour { get; set; } public string Text { get; set; } public bool IsHovering { get; set; } public Action OnClick { get; set; } public Button(Texture2D texture) : this(texture, null) { } public Button(Texture2D texture, SpriteFont font) { _texture = texture; _font = font; Text = ""; PenColour = Color.White; } public override void Update(GameTime gameTime) { _previousMouse = _currentMouse; _currentMouse = Mouse.GetState(); var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1); IsHovering = false; _colour = Color.White; if (mouseRectangle.Intersects(Rectangle)) { IsHovering = true; _colour = Color.Yellow; if (_previousMouse.LeftButton == ButtonState.Pressed && _currentMouse.LeftButton == ButtonState.Released) { OnClick?.Invoke(); } } } public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) { spriteBatch.Draw(_texture, Position, _colour); if (_font != null) { var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2); var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2); spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour); } } } }