learningPixi icon indicating copy to clipboard operation
learningPixi copied to clipboard

Keyboard movement duplicates on game reset

Open CloverFeywilde opened this issue 8 years ago • 1 comments

In your guide, you give instructions on how to execute keyboard commands. Well, I've implemented your example code, and it works. But the problem lies in when I get a gameover and need to restart everything. If I try running a gameover function that resets everything and reruns the setup() function, I end up with all of my keyboard inputs getting duplicated somehow and executing multiple times per button press. I think this has to do with the event listeners being added to the window, but is there any way I can get around this?

Thanks.

function keyboard(keyCode) {
  var key = {};
  key.code = keyCode;
  key.isDown = false;
  key.isUp = true;
  key.press = undefined;
  key.release = undefined;
  //The `downHandler`
  key.downHandler = function(event) {
    if (event.keyCode === key.code) {
      if (key.isUp && key.press) key.press();
      key.isDown = true;
      key.isUp = false;
    }
    event.preventDefault();
  };

  //The `upHandler`
  key.upHandler = function(event) {
    if (event.keyCode === key.code) {
      if (key.isDown && key.release) key.release();
      key.isDown = false;
      key.isUp = true;
    }
    event.preventDefault();
  };

  //Attach event listeners
  window.addEventListener(
    "keydown", key.downHandler.bind(key), false
  );
  window.addEventListener(
    "keyup", key.upHandler.bind(key), false
  );
  return key;
}

CloverFeywilde avatar Jul 12 '17 19:07 CloverFeywilde

I’m new to PIXI, but I think you could initialize keyboard objects at global level, outside any function. So that they are not re-initialized. I’m not sure about this

DjDeveloperr avatar Mar 20 '20 12:03 DjDeveloperr