【发布时间】:2016-05-10 11:00:55
【问题描述】:
我创建了一个按钮类,并在主游戏类中调用它。但它没有开火。实际上,当我单击鼠标左键时,我想触发 Button 类内部的 Update 方法。我正在通过 Debug.WriteLine 检查所有鼠标事件,一切正常。有什么问题?
GameBase 类
public class GameBase : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
Button btn;
public GameBase()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
graphics.PreferredBackBufferWidth = 600;
graphics.PreferredBackBufferHeight = 400;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
btn = new Button(Content.Load<Texture2D>("Sprites/Button"), new Vector2(150, 150));
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
MouseState mouse = Mouse.GetState();
//Debug.WriteLine(mouse);
if (btn.Clicked == true)
{
Debug.WriteLine("Clicked");
currentState = GameState.Playing;
btn.Update(mouse);
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(Content.Load<Texture2D>("Sprites/StartBg"), new Rectangle(0, 0, _screenWidth, _screenHeight), Color.White);
btn.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
按钮类
public class Button
{
public bool Clicked { get; set; }
private Texture2D _image;
private Rectangle _rectangle, _mouseRectangle;
private Vector2 _coordinate;
private Color _color;
private bool _down;
public Button(Texture2D image, Vector2 coordinate)
{
_image = image;
_coordinate = coordinate;
}
public void Update(MouseState mouse)
{
mouse = Mouse.GetState();
_rectangle = new Rectangle((int)_coordinate.X, (int)_coordinate.Y, _image.Width, _image.Height);
_mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1);
if (_mouseRectangle.Intersects(_rectangle))
{
if (_color.A == 255)
_down = false;
if (_color.A == 0)
_down = true;
if (_down)
{
_color.A += 3;
}
else
{
_color.A -= 3;
}
if (mouse.LeftButton == ButtonState.Pressed)
{
Clicked = true;
}
else if (_color.A < 255)
{
_color.A += 3;
Clicked = false;
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(_image, _coordinate, Color.White);
}
}
【问题讨论】: