0

I have a Spaceship object that has 2 methods. First method is move()

char touche;

if(_kbhit() != 0)
{
    touche = _getch();
    if(touche == 'k' || touche == 'l')
    {
        modifyPosition(touche);
    }
}

Second method is shoot()

char touche;

if(_kbhit() != 0)
{
    touche = _getch();
    if(touche == char(32))
    {
        if(nbLasers < 30)
        {
            addLaser();
            compteur++;
        }
    }
}

Both methods are called in a while, one after the other, so the second method almost never works, because I would need to be pressing "Space" exactly after it has went through the move() method. I want to keep the 2 methods seperated, is there a way to make this work?

  • Registered key press will be buffered until `getch`ed. Probably, you could add small delay before checking for spacebar press? The event will wait in the keyboard buffer. – Roman Saveljev Mar 30 '13 at 17:44
  • I don't want to add a delay, because that would stop the game for a certain amount of time. –  Mar 30 '13 at 17:54

1 Answers1

0

One simple approach would be to make a new method read_keyboard().

That function should store the keyboard state, and your other methods can just read that stored state.

if(_kbhit() != 0)
{
    // I'm only explicitly writing "this->" to show that it's a member variable.
    this->touche = _getch();
}
else
{
    this->touche = 0;
}

For example, move now simply becomes:

if(touche == 'k' || touche == 'l')
{
    modifyPosition(touche);
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180