Component.cs
public abstract class Component
//abstract to it has to be inherited and any child will be
//forced to use the Draw & Update class
{
public abstract void Draw(GameTime gameTime, SpriteBatch spriteBatch);
public abstract void Update(GameTime gameTime);
}
Button.cs
public abstract class Button : Component
//abstract to it has to be inherited and any child will be
//forced to use the Draw & Update class
{
// #region Fields
private MouseState _currentMouse;
private SpriteFont _font;
private MouseState _previousMouse;
private Texture2D _texture;
// #endregion
public event EventHandler Click;
public Color TextColour { get; set; }
public Vector2 Position { get; set; }
public Rectangle Rectangle
{
get
{
return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height);
}
}
public string Text { get; set; }
public Button(Texture2D texture, SpriteFont font)
{
_texture = texture;
_font = font;
TextColour = Color.White;
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
var colour = Color.White;
spriteBatch.Draw(_texture, Rectangle, colour);
if (!string.IsNullOrEmpty(Text))
{
var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
//center the font within the button
spriteBatch.DrawString(_font, Text, new Vector2(x, y), TextColour);
}
}
public override void Update(GameTime gameTime)
{
_previousMouse = _currentMouse;
_currentMouse = Mouse.GetState();
//sets position of the mouse to actual current position
if (_currentMouse.LeftButton == ButtonState.Released & _previousMouse.LeftButton == ButtonState.Pressed)
{
Click?.Invoke(this, new EventArgs());
//if click event handler is != null ....use it
}
}
}
我设置了这些课程来注册我的游戏按钮。
在game1.cs中,我尝试添加以下内容来加载内容。
_spriteBatch = new SpriteBatch(GraphicsDevice);
var randomButton = new Button(Content.Load<Texture2D>("Controls/Button"), Content.Load<SpriteFont>("Fonts/Font"))
{
};
当实现这一点时,我得到错误代码CS0144";无法创建实例、抽象类型或接口"Button";
在game1的顶部,我正在使用名称空间。控件作为按钮位于名为Controls的文件夹中。欢迎就此提供任何协助或建议。
按钮为什么是abstract
?,抽象类型不能用new关键字初始化,相反,它们的构造函数被认为是抽象的,派生类型应该对其调用base()
,如果可能的话,请考虑不抽象类Button(可能的意思是:如果你有任何抽象成员,则不可能,否则,是的)。