kittykatattack / learningPixi

A step-by-step introduction to making games and interactive media with the Pixi.js rendering engine.
4.4k stars 849 forks source link

Keyboard movement duplicates on game reset #65

Open CloverFeywilde opened 7 years ago

CloverFeywilde commented 7 years ago

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;
}
DjDeveloperr commented 4 years ago

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