1

在构造函数中我做了:

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但从未进入它。

那么我该如何让它工作呢?以及如何使鼠标左键双击而不是单击?

4

1 回答 1

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;
}
于 2013-10-20T17:47:07.127 回答