Skip to main content
GameDev.net gamedev.net
🔒 Locked

KeyPressed SDL.NET

Started by kiketom Oct 11, 2006 at 6:39 AM 2 replies 1.3k views
Original Post
kiketom
kiketom
Hi! all I have this code, and i don't know why the LeftArrow event is only repeated 1 time while the key is pressed. I need to press several times to move the piece several spaces. The movement isn't continuous .. :?

public override void HandleKeyboardEvents(SdlDotNet.KeyboardEventArgs e)
        {
            try
            {
                switch (e.Key)
                {
                    case Key.DownArrow:
                        _map.CurrentPieceMoveDown();
                        break;
                    case Key.LeftArrow:
                        _map.CurrentPieceMoveLeft();
                        Console.WriteLine("LeftArrow Pressed");
                        break;
                    case Key.RightArrow:
                        _map.CurrentPieceMoveRight();
                        break;
                    case Key.UpArrow:
                        _map.CurrentPieceRotate();
                        break;
                }
            }
            catch (SdlException)
            {
            }
        }



Tomy
Emmanuel Deloget
Emmanuel Deloget
Key press events are filtered by the hardware IIRC. You get one once, then the system waits for some time, then you get a bunch of them every few milliseconds until you stop pressing the key.

Sdl might filter this even better, by not sending you the additional keypress event that your hardware might generate. You get a keypress when you press the key, and nothing until you stop pressing the key.

What you want is different: you want to register a keypress, and then perform an action repeatively until you stop pressing the key. This can be done using this algorithm (pseudo-code):

key_state  keys[nb_keys]; // hold the state of the keysfunction handle_keyboard_event(kb_event)  if kb_event is "key press"    keys[kb_event.corresponding_key] = pressed;  else if kb_event is "key release"    keys[kb_event.corresponding_key] = released;  endiffunction main_game_loop()  if I need to process keyboard events    kb_event = get_keyboard_event()    handle_keybord_event(kb_event)  endif    // now I can play with my keys  if keys[Key.DownArrow] is pressed    _map.MoveCurrentPieceDown()  else if (keys[Key.LeftArrow] is pressed    _map.MoveCurrentPieceLeft()  else ...

HTH,
Perost
Perost
You might also be interested in SDL_EnableKeyRepeat. Emmanuel's solution is better in my opinion though.
kiketom
kiketom
OK, thx all.
Tomy

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.