我是XNA的新手,我正在尝试创建一个简单的游戏菜单,并且我使用矩形作为菜单项。我有一个名为Game1.cs
的主类和一个矩形的不同类,它应该在点击时关闭游戏,称为_exitGame.cs
。到目前为止,我已经得到了这个 -
在主类中,我初始化一个类变量:
_exitGame exitGame;
我加载纹理和矩形:
exitGame = new _exitGame(Content.Load<Texture2D>("exitGame"), new Rectangle(50, 250,300,50));
我已为该课程创建了更新代码:
exitGame.Update(gameTime);
我绘制矩形:
exitGame.Draw(spriteBatch);
在我的_exitGame
课程中,我有这个:
class _exitGame
{
Texture2D texture;
Rectangle rectangle;
public _exitGame(Texture2D newTexture, Rectangle newRectangle)
{
texture = newTexture;
rectangle = newRectangle;
}
public void LoadContent()
{
}
public void Update(GameTime gametime)
{
var mouseState = Mouse.GetState();
var mousePosition = new Point(mouseState.X, mouseState.Y);
var recWidth = rectangle.Width;
var recHeight = rectangle.Height;
if (rectangle.Contains(mousePosition))
{
rectangle.Width = 310;
rectangle.Height = 60;
}
else
{
rectangle.Width = 300;
rectangle.Height = 50;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, rectangle , Color.White);
}
}
现在我所拥有的是一个矩形,可以在鼠标悬停时改变其大小。之前我使用代码this.Close();
在键盘按钮点击关闭游戏,但由于我无法在这种情况下使用它,我有点困惑如何实现此功能。关于如何做到这一点的任何提示?
答案 0 :(得分:1)
指出你正确的方向:
首先,exitGame看起来像是我的游戏组件。那你为什么不把它变成一个游戏组件。由于您要执行绘图,因此它必须是drawableGameComponent。您可以使用Components.Add(new MyDrawableGameComponent);
gameComponent就像你的Game1类一样持有gmae。所以现在只需要Game.Close()
课来关闭你的游戏。
祝你好运并对gamecomponents和drawableGameComponents进行一些搜索。
答案 1 :(得分:1)
通过调用Exit() method in your Game class可以实现关闭XNA游戏。
在您的情况下,您可以在_exitGame类中引发一个事件
class _exitGame
{
public event EventHandler ExitRequested = delegate {};
Texture2D texture;
Rectangle rectangle;
public _exitGame(Texture2D newTexture, Rectangle newRectangle)
{
texture = newTexture;
rectangle = newRectangle;
}
public void LoadContent()
{
}
public void Update(GameTime gametime)
{
var mouseState = Mouse.GetState();
var mousePosition = new Point(mouseState.X, mouseState.Y);
var recWidth = rectangle.Width;
var recHeight = rectangle.Height;
if (rectangle.Contains(mousePosition))
{
rectangle.Width = 310;
rectangle.Height = 60;
if (mouseState.LeftButton == ButtonState.Pressed)
{
ExitRequested(this, EventArgs.Empty);
}
}
else
{
rectangle.Width = 300;
rectangle.Height = 50;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, rectangle , Color.White);
}
}
并在您的游戏课程中订阅该活动
exitGame = new _exitGame(Content.Load<Texture2D>("exitGame"), new Rectangle(50, 250,300,50));
exitGame.ExitRequested += (s, e) => Exit();
几点说明:
public event EventHandler ExitRequested = delegate {};
mouseState.LeftButton == ButtonState.Pressed
表达式将返回true,而不仅仅是第一次点击。只要您使用它来退出游戏就可以了,但对于更新周期将继续运行的其他场景,您应该将鼠标状态存储在上一个更新周期中,另外还要检查上一个周期中是否未按下鼠标状态并按下当前抓住点击事件。答案 2 :(得分:0)
事件通常是一种很好的方法。现在,由于您已经找到了一种方法来了解按钮被按照自己的方式单击的时间,我们可以通过调用Close
对象的Game
函数来关闭游戏。因此,对于此解决方案,您基本上需要引用Game
或任何您称为Game类的内容。