实现按键处理持续时间的方法

本文关键字:方法 持续时间 处理 实现 | 更新日期: 2023-09-27 18:30:22

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

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

实现按键处理持续时间的方法

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);
}

要检测单个按键...

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
        }

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

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

// 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);
   ...
}