我正在尝试为游戏制作主菜单,当我点击(或左键单击)某个区域时,我遇到了这些问题。我见过WP7的许多游戏菜单,在你发布点击后它会做一些事情。好吧,我试图在按下时显示图像,并在图像被释放时发出声音。
这怎么可能?
这是我的代码:
//putoClick's = Mouse.GetState();
//clickarea = the same dimensions as putoClick;
if (putoClick.LeftButton == ButtonState.Pressed)
{
mouseClick = new Rectangle(putoClick.X, putoClick.Y, 30, 20);
if (clickArea.Intersects(mouseClick))
{
spriteBatch.Draw(imgB, btnPos, Color.White);
btnMenuClickSound.Play();
}
else
{
spriteBatch.Draw(imgBs, btnPosN, Color.White);
}
putoClick = Mouse.GetState();
//....
}
相反,按下按钮时会不断播放声音。尝试与媒体合作并发布,但没有奏效。请原谅我的变量名称大声笑它是一个快速测试。提前致谢
答案 0 :(得分:3)
您需要做的是创建一个保留两种鼠标状态的鼠标处理类。这个框架和前一个框架的。并检查这两种状态之间按钮状态的变化。
之类的东西MouseState newState = Mouse.getState();
if(oldState.LeftButton == ButtonState.Pressed && newState.LeftButton == ButtonState.Released){
// click released
// TODO : add your on released code here
}
if(newState.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released)
{
// pressed for the first time
// TODO : add your on clicked code here
}
if(newState.LeftButton == ButtonState.Pressed)
{
// left mouse button is down
// TODO : add your on left button down logic
}
// "remember" this frame's state for use in the next frame.
oldState = newState;
你每帧(更新)调用这个方法就完成了。 (您可能希望通过让鼠标处理程序类只更新内部布尔值并让您的游戏代码在需要时读取此布尔值来完全分离逻辑输入,但这取决于您的游戏需求。
答案 1 :(得分:1)
你在这里写的是:
如果按下按钮,请执行A. 如果没有按下按钮,请执行B
你想写的是
如果按下按钮而不是等待按钮没有被按下而且仅按下B
诀窍是让按钮保持最后状态
答案 2 :(得分:1)
声音持续播放的原因是因为btnMenuClickSound.Play();
调用在2 if
条件内发生,声明如下:
因此,虽然这两个条件都是正确的,但你的声音会播放。
因此,移动一些代码并使用布尔标志来跟踪您是否点击按钮,如果该状态发生了变化,我们可以找到解决方案!
// a private class member - NOT to be declared within the function
bool buttonClicked = false;
if (putoClick.LeftButton == ButtonState.Pressed)
{
mouseClick = new Rectangle(putoClick.X, putoClick.Y, 30, 20);
//if the button was clicked with the left mouse button
//buttonClicked will be true, otherwise false.
buttonClicked = clickArea.Intersects(mouseClick);
}
else if(buttonClicked && putoClick.LeftButton == ButtonState.Released)
{
//The button was clicked last frame, but the mouse is now up
//play the sound!
btnMenuClickSound.Play();
}
//the mouse button is released, therefore the button is not clicked
if(putoClick.LeftButton == ButtonState.Released)
buttonClicked = false;
//draw the appropriate graphic depending on
//whether or not the button has been clicked.
if(buttonClicked)
spriteBatch.Draw(imgB, btnPos, Color.White);
else
spriteBatch.Draw(imgBs, btnPosN, Color.White);
putoClick = Mouse.GetState(); //also, i presume this needs to be here instead?
我决定跟踪按钮是否被点击,因为我的理解是只有在点击按钮后释放鼠标时才会播放要播放的声音。