为了处理文本输入,您需要知道何时按下或释放某个键。不幸的是,XNA 的 KeyboardState 对此并没有真正的帮助,所以你必须自己做。基本上,您只需将当前更新的 PressedKeys 与上一次更新的 PressedKeys 进行比较。
public class KbHandler
{
private Keys[] lastPressedKeys;
public KbHandler()
{
lastPressedKeys = new Keys[0];
}
public void Update()
{
KeyboardState kbState = Keyboard.GetState();
Keys[] pressedKeys = kbState.GetPressedKeys();
//check if any of the previous update's keys are no longer pressed
foreach (Keys key in lastPressedKeys)
{
if (!pressedKeys.Contains(key))
OnKeyUp(key);
}
//check if the currently pressed keys were already pressed
foreach (Keys key in pressedKeys)
{
if (!lastPressedKeys.Contains(key))
OnKeyDown(key);
}
//save the currently pressed keys so we can compare on the next update
lastPressedKeys = pressedKeys;
}
private void OnKeyDown(Keys key)
{
//do stuff
}
private void OnKeyUp(Keys key)
{
//do stuff
}
}
给你的 Game 类一个 KbHandler,并从你的 Game 的 update 方法中调用它的 Update 方法。
(顺便说一句,比较两个数组可能比使用 foreach 和 Contains 更有效,但是要比较的项目很少,我怀疑它是否重要。)