c++allegro5

Continuous keyboard movements


Now I am making a game where there are two plates on both sides of the screen (i.e. Left and right). And a ball which bounces in the screen. When it touches either of the plates then it bounces back. But if it touches left or right edge of the screen then it's game over. We have to control the plates by arrow keys or standard (W, A, S, D) keys. Now my problem is when I press W or any movement keys it moves once then stops.

I have to press it many times to make it move. I want continuous movement when I press and hold any of my movement keys. I am using allegro 5 with Dev c++ on windows 7 PC.


Solution

  • You need to track the state of the keys. When you get a key down event, set the keydown to true. When you get a key up event, set the keydown to false.

    Then in your update function, check if the key is down and then move.

    Something like this makes it very easy :

    bool keys[ALLEGRO_KEY_MAX] = {0};
    
    /// In event loop
    if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
       keys[ev.keyboard.keycode] = true;
    }
    else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
       keys[ev.keyboard.keycode] = false;
    }
    
    if (ev.type == ALLEGRO_EVENT_TIMER) {
       if (keys[ALLEGRO_KEY_W]) {
          player.y -= YSPEED;
       }
       if (keys[ALLEGRO_KEY_S]) {
          player.y += YSPEED;
       }
    }
    

    You can also monitor the keyboard state with al_get_keyboard_state, but it's not guaranteed to be accurate due to the time difference between when allegro receives a key event and you do.