Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Keyboard input - restrict to one key at a time  (Read 4058 times)

0 Members and 1 Guest are viewing this topic.

Askr

  • Newbie
  • *
  • Posts: 6
    • View Profile
Keyboard input - restrict to one key at a time
« on: July 09, 2012, 10:07:09 am »
[edit: solved, I guess]

Hi there,

I'm currently developing a game using SFML.net and it's been going smooth for quite a while.
My problem now is that by holding one direction key and then pressing another, the player can walk one more tile than he should be able to. Here's the corresponding code for reference:

Code: [Select]
static void OnKeyPress(object sender, EventArgs e)
        {
            if (Keyboard.IsKeyPressed(Keyboard.Key.Numpad7))
            {
                player.move(-1, -1);
            }
            else if (Keyboard.IsKeyPressed(Keyboard.Key.Numpad8) || Keyboard.IsKeyPressed(Keyboard.Key.Up))
            {
                player.TileID = TileSet.Up;
                player.move(0, -1);
            }
            else if (Keyboard.IsKeyPressed(Keyboard.Key.Numpad9))
            {
                player.move(1, -1);
            }
            [...]
}

[...]

MainWindow.KeyPressed +=new EventHandler<KeyEventArgs>(OnKeyPress);
And so on.

Is there a special way to do things? Before SFML.net I've been using methods like Console.ReadKey() that pause the program until they are given one key. I've been trying to accomplish something alike using a GameState variable that I would set to PAUSE before I enter a loop in which the key presses are being handled and then return PLAYING, but that only stopped my program from exiting correctly (debug still running, music still playing, ...) when I closed the window.

Any help is appreciated as I'm still quite a newbie. Also if you need more information ask straight away. :)

-------

Well... As I read through the forums a bit I noticed something about these GameStates I previously had been missing out: You should also check within the method handling the input wether the current State is accepting keys. I previously completely forgot about that. Also, I just left out the extra loop now and all the previous problems about not exiting correctly stay gone. Sorry about this new thread, but maybe it can help someone in the future. :D

Also I'd be interested in the "professional" way to handle keys. I'm not working after a big plan here - just thinking and improvising; then optimizing my way out of the mess I created in the first place. :)
« Last Edit: July 09, 2012, 10:18:32 am by Askr »

 

anything