Enter text in XNA (for entering names, conversations)

I am trying to implement keyboard text input for chatting, entering a character name, saving a file name, etc.

I was messing around with KeyboardState, trying to get the newly added character to translate into a character that I could add to my input line, but it seems to sort the array of keys pressed in a specific order (I'm sure it is sorted by keycode), so I'm not I can easily find which key was last pressed to add it to the input line.

Is there an easy way to detect the last pressed text key (including situations where several keys are pressed because people sometimes do this), or is it easier to use some existing solutions?

I am learning C # and XNA, so I would like to be able to do it myself, but in the end I want my game to work.

+6
source share
2 answers

To handle text input, you need to know when a key is pressed or released. Unfortunately, the XNA KeyboardState doesn't really help with this, so you need to do it yourself. Basically, you just need to compare the current update by pressing the keys with the keys pressed from the previous update.

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

Give the game class KbHandler and name it "Update Method" from your game update method.

(By the way, perhaps a more efficient way to compare two arrays than with foreach and Contains, but with so many elements to compare, I doubt it will matter.)

+6
source

You can try the example below here

 KeyboardState keybState = Keyboard.GetState(); if (keybState.IsKeyDown(Keys.Left)) { // process left key } if (keybState.IsKeyDown(Keys.Right)) { // process right key } 

This will work simultaneously with a few keystrokes. If you want to avoid this, add else before the second if (and the following)

In addition, the held key will trigger several events with a keystroke - if this is undesirable, you will need to enter a state variable that you flip when the key is down and when not, and execute it when the key is pressed

0
source

Source: https://habr.com/ru/post/913202/


All Articles