Button XNA按钮悬停
我的游戏里有一个按钮。我想让它在鼠标悬停在按钮上时切换为其他按钮图像,在鼠标不在按钮上时切换回其他按钮图像 问题是当鼠标离开按钮矩形区域时,它不会变回第一个图像 我的代码如下:Button XNA按钮悬停,button,xna,Button,Xna,我的游戏里有一个按钮。我想让它在鼠标悬停在按钮上时切换为其他按钮图像,在鼠标不在按钮上时切换回其他按钮图像 问题是当鼠标离开按钮矩形区域时,它不会变回第一个图像 我的代码如下: public override void Update(GameTime gameTime) { base.Update(gameTime); MouseState mouseState; mouseDiBack = false; mous
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);
}
}
}
你知道我该怎么做吗?当鼠标移出范围区域时,你没有将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;
}
}
正如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;
相当简单的解决方案,您没有将图像设置回鼠标未悬停的情况
if (new Rectangle(mouseState.X, mouseState.Y, 1, 1).Intersects(backButtonRectangle))
{
backButton = backButtonHilite;
}
else
{
backButton = originalImage; //whatever your Texture2D object may be called
}
不要指望机器知道你想切换回来!机器是愚蠢的。。好的,这实际上是因为您重写了变量的值,而没有重置它