MonoGame按键琴弦 [英] MonoGame Key Pressed String

查看:126
本文介绍了MonoGame按键琴弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MonoGame中,如何读取以String形式按下的键盘键?

In MonoGame, how can I read which keyboard key is pressed in the form of a String?

我尝试过String pressedKey = Keyboard.GetState().ToString();,但是它给了我"Microsoft.Xna.Framework.Input.KeyboardState".

I have tried String pressedKey = Keyboard.GetState().ToString();, but it gives me "Microsoft.Xna.Framework.Input.KeyboardState".

推荐答案

在游戏中,您通常将按键视为具有状态而不是字符串的按键,因为您通常会检查按键是否向上或向下移动字符,射击,跳跃等.

In games, you typically think of keys as buttons that have state rather than strings because you are usually checking if a button is up or down to move a character around, shoot, jump, etc.

正如其他人所说,您说如果已经知道要测试哪些密钥,则应该使用IsKeyDown和IsKeyUp.但是,有时您只想知道按下了哪些键.为此,您可以使用GetPressedKeys方法,该方法将为您提供一系列当前在键盘上按下的键.

As others have said, you said you should use IsKeyDown and IsKeyUp if you already know what keys you want to test. However, sometimes you just want to know what keys are being pressed. For that, you can use the GetPressedKeys method which will give you an array of keys currently pressed on the keyboard.

如果要将这些键转换为字符串,则可以在更新方法中执行类似的操作.

If you wanted to turn those keys into a string, you could probably do something like this in your update method.

    private string _stringValue = string.Empty;

    protected override void Update(GameTime gameTime)
    {
        var keyboardState = Keyboard.GetState();
        var keys = keyboardState.GetPressedKeys();

        if(keys.Length > 0)
        {
            var keyValue = keys[0].ToString();
            _stringValue += keyValue;
        }

        base.Update(gameTime);
    }

但是,请记住,这并不完美.您必须添加额外的代码来处理大写和小写字母的SHIFT键,并且您想过滤掉其他键,例如Ctrl和Alt.也许将输入限制为仅字母数字值,依此类推.

However, keep in mind that this won't be perfect. You'd have to add extra code to handle the SHIFT key for upper and lowercase letters and you would want to filter out other keys like Ctrl and Alt. Perhaps restrict the input to only alphanumeric values and so on..

祝你好运.

这篇关于MonoGame按键琴弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆