1

我正在尝试为游戏制作主菜单,当我在某个区域上点击(或左键单击)时遇到了这些问题。我见过许多 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();

    //....
}

相反,只要按下按钮,声音就会不断播放。尝试与新闻稿合作,但没有奏效。请原谅我的变量名,哈哈,这是一个快速测试。提前致谢

4

3 回答 3

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;

你每帧调用这个方法(更新),你就完成了。(您可能希望通过让鼠标处理程序类只更新一个内部布尔值并让您的游戏代码在需要时读取该布尔值来将输入与逻辑完全分开,但这取决于您的游戏需求。

于 2013-04-02T06:00:40.640 回答
1

你在这里写的是:

如果按下按钮执行 A 如果未按下按钮执行 B

你想写的是

如果按钮被按下而不是等待按钮未被按下并且仅比 B

诀窍是保持按钮的最后状态

于 2013-04-02T05:58:18.223 回答
1

声音继续播放的原因是因为btnMenuClickSound.Play();呼叫发生在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?

我决定跟踪按钮是否被单击,因为我的理解是,要播放的声音应该只在单击按钮后释放鼠标时播放。

于 2013-04-02T06:01:59.853 回答