我的游戏中有一个按钮。当鼠标悬停在其上时,我想让它更改为其他按钮图像,当鼠标不在按钮中时,我想更改回来。
问题是当鼠标从按钮矩形区域退出时,它不会变回第一个图像
我的代码是这样的:
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
MouseState mouseState;
mouseDiBack = false;
mouseState = Mouse.GetState();
if (new Rectangle(mouseState.X, mouseState.Y, 1, 1).Intersects(backButtonRectangle))
{
backButton = backButtonHilite;
}
if ((mouseState.LeftButton == ButtonState.Pressed) &&
(new Rectangle(mouseState.X, mouseState.Y, 1, 1).Intersects(backButtonRectangle)))
{
mouseDiBack = true;
}
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Draw(ScoreBG, ScoreBGRectangle, Color.White);
spriteBatch.Draw(backButton, backButtonRectangle, Color.White);
base.Draw(gameTime);
}
}
}
任何想法我怎么做......?
答案 0 :(得分:0)
您没有将backButton设置回鼠标移出示波器区域时的状态。请查看下面的代码,并注意Update函数中添加的ELSE语句。
defaultBackButton = backButton; //Save the default back button somewhere outside your update function
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
MouseState mouseState;
mouseDiBack = false;
mouseState = Mouse.GetState();
if (new Rectangle(mouseState.X, mouseState.Y, 1,1).Intersects(backButtonRectangle))
{
backButton = backButtonHilite;
}
else
{
backButton = defaultBackButton;
}
if ((mouseState.LeftButton == ButtonState.Pressed) && (new Rectangle(mouseState.X, mouseState.Y, 1, 1).Intersects(backButtonRectangle)))
{
mouseDiBack = true;
}
}
答案 1 :(得分:0)
如Jon所说,当鼠标离开矩形时,你需要设置原始纹理。
bool mouseOverBackButton =
mouseX >= buttonRectangle.Left && mouseX <= buttonRectangle.Right &&
mouseY >= buttonRectangle.Top && mouseY <= buttonRectangle.Bottom;
backgroundTexture = mouseOverBackButton ? mouseOverTexture: mouseAwayTexture;
mouseDiBack = mouseState.LeftButton == ButtonState.Pressed && mouseOverBackButton;
答案 2 :(得分:0)
相当简单的解决方案,您没有将图像设置回鼠标未悬停的情况。
if (new Rectangle(mouseState.X, mouseState.Y, 1, 1).Intersects(backButtonRectangle))
{
backButton = backButtonHilite;
}
else
{
backButton = originalImage; //whatever your Texture2D object may be called
}
不要指望机器知道您想要切换回来!机器很蠢! ..Ok,实际上是因为你覆盖了变量的值而没有重置它。