实现按键操作持续时间的方法

时间:2012-04-08 16:26:02

标签: c# input xna keypress

我正在使用XNA(C#)来开发2D平台游戏。 我想知道按住特定按钮的最佳方法。例如,你按住的越多,激光束就越大。

到目前为止,由于我已经使用了保存键盘最后2个状态的输入机制,因此我可以对每个更新周期进行额外检查以增加持续时间。但是,这种方法相当有限,因为它只处理一个特定的按钮(火按钮即),它应该做的伎俩,但我想知道是否有一个更通用的解决方案的问题。

3 个答案:

答案 0 :(得分:1)

float ElapsedSecondsPerFrame = (float) gametime.Elapsed.TotalSeconds;

KeyFirePressedTime = Keyboard.GetState().IsKeyDown(FireKey) 
                         ? (KeyFirePressedTime + ElapsedSecondsPerFrame ) 
                         : 0;

通用方法

Dictionary<int, float> PressedKeysTime = new ...


void Update(float Elapsed)
{
      List<int> OldPressedKeys = PressedKeysTime.Keys.ToList();
      foreach (int key in Keyboard.GetState().GetPressedKeys.Cast<int>())
      {
           if (!PressedKeysTime.ContainsKey(key)) 
           {
                PressedKeysTime[key] = 0;
           } else {
               OldPressedKeys.Remove(key);
               PressedKeysTime[key] += Elapsed;
           }
      }
      foreach (int keynotpressed in OldPressedKeys) 
          PressedKeysTime.Remove(keynotpressed);

}

答案 1 :(得分:0)

检测单个按键...

lastKeyboardState = CurrentKeyState;
CurrentKeyState = Keyboard.GetState();

if ((CurrentKeyState.IsKeyUp(Keys.Enter)) && (lastKeyboardState.IsKeyDown(Keys.Enter))
        {
            //Enter was pressed
        }

检测按下的键......

lastKeyboardState = CurrentKeyState;
CurrentKeyState = Keyboard.GetState();
if (CurrentKeyState.IsKeyDown(Keys.Enter)
        {
            //Enter was pressed (You could do BeamSize++ here
        }

这似乎是最好的方法。这是你已经使用的方法吗?

答案 2 :(得分:0)

这是一个简单的伪代码示例:

// to cancel immediately
if key is pressed this frame, but was released last frame
   begin effect

else if key is pressed this frame, and also was last frame
   increase magnitude of effect

else if key is released this frame and effect is active
   end effect


// or to gradually decrease
if key is pressed this frame, and effect is inactive
   begin effect

else if key is pressed this frame, and effect is active
   increase magnitude of effect

else if key is released this frame and effect is active
   decrease magnitude of effect
   if magnitude decreased enough, end effect

要专门测量持续时间,就像你说的那样:

public void Update(GameTime pGameTime)
{
   private TimeSpan mKeyDuration = TimeSpan.FromSeconds(0);

   ...

   if key is pressed this frame
      mKeyDuration += pGameTime.ElapsedGameTime;

   else if key was pressed last frame
      mKeyDuration = TimeSpan.FromSeconds(0);

   ...
}