我是XNA的新手。我正在制作一款需要关卡编辑器的游戏。我需要一个文本框来获取级别名称及其描述。所以我写了这样的代码:
if (isSaveBox)
{
KeyboardState ks = Keyboard.GetState();
Keys[] keys = ks.GetPressedKeys();
Keys tempKey = Keys.None;
foreach (Keys key in keys)
{
Keys currentKey = key;
if (ks.IsKeyUp(lastKey))
{
string toadd = key.ToString();
if (!(key == Keys.None) && key != Keys.Space && key != Keys.Back && key != Keys.Enter)
{
levelName += toadd;
}
else if (key == Keys.Space)
{
levelName += " ";
}
else if (key == Keys.Back)
{
levelName.Remove(levelName.Length - 1);
lastKey = currentKey;
}
}
if (currentKey != Keys.None && ks.IsKeyDown(currentKey))
{
tempKey = currentKey;
}
}
lastKey = tempKey;
message = "Save level" + "\n" + "Enter - yes / Esc - no" + "\n" + levelName;
但是当我尝试输入一些字母时,它们不会被添加到levelName
字符串中。有人可以帮我吗?
答案 0 :(得分:3)
据我所知,你的代码运行正常。我玩了它并添加了一些改进。你不需要一些东西,我就这么做了,当你按住一个键时,它不会那么快就发送垃圾邮件。我会添加对其他键(如符号和大写)的支持,但对于所有这些键,这是一个很长的切换语句,因此您可以查看this文章并轻松实现。
我添加了一些变量,所有与文本框相关的内容现在应该读作
Keys[] lastKeys;
KeyboardState lastKeyboardState;
public double timer;
public string levelName;
如果需要,您还可以将currentKeyboardState
变量添加为全局变量。
现在对于代码,我将其拆分为2种方法,以防止必须复制代码两次
if (isSaveBox)
{
//Get the current keyboard state and keys that are pressed
KeyboardState keyboardState = Keyboard.GetState();
Keys[] keys = keyboardState.GetPressedKeys();
foreach (Keys currentKey in keys)
{
if (currentKey != Keys.None)
{
//If we have pressed the same key twice, wait atleast 125ms before adding it again
if (lastKeys.Contains(currentKey))
{
if ((gameTime.TotalGameTime.TotalMilliseconds - timer > 125))
HandleKey(gameTime, currentKey);
}
//If we press a new key, add it
else if (!lastKeys.Contains(currentKey))
HandleKey(gameTime, currentKey);
}
}
//Save the last keys and pressed keys array
lastKeyboardState = keyboardState;
lastKeys = keys;
}
重置计时器并实际找出字符串的方法(这是你要为shift和符号添加代码的地方等)
private void HandleKey(GameTime gameTime, Keys currentKey)
{
string keyString = currentKey.ToString();
if (currentKey == Keys.Space)
levelName += " ";
else if ((currentKey == Keys.Back || currentKey == Keys.Delete) && levelName.Length > 0)
levelName = levelName.Remove(levelName.Length - 1);
else if (currentKey == Keys.Enter)
return;
else
levelName += keyString;
//Set the timer to the current time
timer = gameTime.TotalGameTime.TotalMilliseconds;
}
您还可以使用StringBuilder
进行进一步优化。
如果您想继续编写自己的用户界面,请继续。我仍然建议使用UI库(我使用新复制的Neoforce Controls),但对here的讨论有更大的讨论。
答案 1 :(得分:1)