如何检查鼠标左键是否双击?

时间:2013-10-20 17:01:11

标签: c# xna xna-4.0

在我做的构造函数中:

mouseState = Mouse.GetState();
var mousePosition = new Point(mouseState.X, mouseState.Y);

然后在我创建的输入法中添加了:

private void ProcessInput(float amount)
{
     Vector3 moveVector = new Vector3(0, 0, 0);
     KeyboardState keyState = Keyboard.GetState();
     if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W))
         moveVector += new Vector3(0, 0, -1);
     if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S))
         moveVector += new Vector3(0, 0, 1);
     if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
         moveVector += new Vector3(1, 0, 0);
     if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
         moveVector += new Vector3(-1, 0, 0);
     if (keyState.IsKeyDown(Keys.Q))
         moveVector += new Vector3(0, 1, 0);
     if (keyState.IsKeyDown(Keys.Z))
         moveVector += new Vector3(0, -1, 0);
     if (keyState.IsKeyDown(Keys.Escape))
     {
         this.graphics.PreferredBackBufferWidth = 800;
         this.graphics.PreferredBackBufferHeight = 600;
         this.graphics.IsFullScreen = false;
         this.graphics.ApplyChanges();
     }
     if (mouseState.LeftButton == ButtonState.Pressed)
     {
         this.graphics.PreferredBackBufferWidth = 1920;
         this.graphics.PreferredBackBufferHeight = 1080;
         this.graphics.IsFullScreen = true;
         this.graphics.ApplyChanges();
     }

     AddToCameraPosition(moveVector * amount);
 }

我补充说:

if (mouseState.LeftButton == ButtonState.Pressed)
{
    this.graphics.PreferredBackBufferWidth = 1920;
    this.graphics.PreferredBackBufferHeight = 1080;
    this.graphics.IsFullScreen = true;
    this.graphics.ApplyChanges();
}

我使用了一个断点,当点击鼠标左键时它什么也没做。 它永远不会进入if块。 它到达if但从未进入。

那么如何让它发挥作用呢? 如何双击鼠标左键而不是单击?

1 个答案:

答案 0 :(得分:7)

首先,您必须致电

mouseState = Mouse.GetState()

在每个Update()循环中。对你而言,这可能是在ProcessInput方法的开头。

其次,即便如此,您编写的代码也无效。你的代码现在几乎说“只要按下左键,就把游戏切换到全屏。” XNA不是事件驱动的 - 没有OnClick或OnDoubleClick事件,您必须自己实现这些事件或使用可用的属性。

您可能希望实现这样的功能:

MouseState previousState;
MouseState currentState;
bool WasMouseLeftClick()
{
    return (previousState.LeftButton == ButtonState.Pressed) && (currentState.LeftButton == ButtonState.Released);
}

然后,在ProcessInput函数中,将其添加到开头:

previousState = currentState;
currentState = Mouse.GetState();

你可以使用它:

if (WasMouseLeftClick())
{
    // Switch to fullscreen.
}

添加一个会对双击产生反应的功能会稍微复杂一些。您必须定义点击之间允许的最大延迟。然后,每个周期,如果您有一个点击,您将需要检查最后一次点击发生的时间。如果它比延迟时间短,我们有双击。像这样:

const float MAXDELAY = 0.5f; // seconds
DateTime previousClick;
bool WasDoubleClick()
{
   return WasMouseLeftClick() // We have at least one click, and
       && (DateTime.Now - previousClick).TotalSeconds < MAXDELAY;
}

此外,您需要将其添加到ProcessInput的末尾:(注意,您必须在检查双击后添加此项,否则它会将您的所有点击解释为双倍)

if (WasMouseLeftClick())
{
  previousClick = DateTime.Now;
}