我正在使用 XNA (C#) 开发 2D 平台游戏。我想知道处理按住特定按钮的最佳方法。例如,您按住的越多,激光束就越大。
到目前为止,由于我已经在使用保存键盘最后两种状态的输入机制,我可以在每个更新周期进行额外检查以增加持续时间。但是,这种方法相当有限,因为它只处理一个特定的按钮(即触发按钮),它应该可以解决问题,但我想知道是否有更通用的解决方案。
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);
...
}