Jump to content

Which is more efficient for input checks: listeners or update?


MishaShapo
 Share

Recommended Posts

I've seen several tutorials do something like:

update: function(){  if(this.cursors.up.isDown || this.game.input.activePointer.isDown){    //Start jump sequence  } else if(this.cursors.up.isUp || this.game.input.activePointer.isUp){    //End jump sequence  }}

And other do this :

create: function(){  this.game.input.onDown.add(function(){    //Start jump sequence  });  this.game.input.onUp.add(function(){    //End jump sequence  });}

Are there any significant differences between the two? Is one more efficient than the other?

 

Thank you for your responses. =) This has been bugging me for a while. =)

Link to comment
Share on other sites

The update loop approach is good for processes that should continue while a condition is met, like for example 'accelerate while the arrow key is down'. You wouldn't want to use a signal/event for that.

In your update code example above you should consider that jump will be triggered repeatedly on each update while the mouse button is down. You need an additional condition to check that the button was only just pressed this update cycle.

So it's not so much a case of one approach being more efficient than another, more that each is suited to checking for different kinds of input.

Link to comment
Share on other sites

Theres no problem with the anonymous function, it'll only get created once and passed as a callback to the event, however, you cant remove anonymous functions from native event emitters.

 

I'm not sure if Phaser implements a synthetic event layer (dont think it does) so its basically the same as attaching to a native `keydown` listener. This is great in general practise, pub/sub only executes the code when its necessary so tries to be resource-light, but, for games the key events in browsers arent always ideal, mainly due to repeat. The repeat speed of the keypress is taken into account and there is always a delay after the first event, which is often undesirable in games.

 

In contrast, the first example, using an update function is doing work when it doesnt have to most of time—youre not pressing all the keys every frame so they are unnecessary checks (yes, effectively the browser is doing this underneath for event listeners, I think, but that'll be a ton quicker and wont block up the JS thread). The upshoot is that you'll get an event with each update, so, if you're running your update every 16ms or so, you know your events will (mostly) arrive every 16ms.

 

I wrote a wrapper that turns keypresses into event streams to solve the repeating key problem. It aims to get the best of both worlds, it'll only emit events when keys are pressed and handles the raw event listeners for you.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...