Jump to content

Keypress hold tracking


Recommended Posts



I'm trying to introduce a function in my game wherein my projectiles will be more accurate the longer you hold the shoot button (spacebar in my case).


What's the best approach for this?


i tried something in my update function like:


if(spaceKey.downDuration(Phaser.Keyboard.SPACEBAR,1)){holdPeriod = 1;}if(spaceKey.downDuration(Phaser.Keyboard.SPACEBAR,800)){holdPeriod = 801;}if(spaceKey.downDuration(Phaser.Keyboard.SPACEBAR,1600)){holdPeriod = 1601;}game.time.events.add(Phaser.Timer.SECOND * 0.5, shoot(holdPeriod), this);
but it always enters the last if statement regardless of how long/quick I hold the spacebar (considering the 2nd argument is in milliseconds).
On another note, I am getting an event error in the last line.
Link to comment
Share on other sites

You need else if statements.
if(spaceKey.downDuration(Phaser.Keyboard.SPACEBAR,1)){holdPeriod = 1;} else if(spaceKey.downDuration(Phaser.Keyboard.SPACEBAR,800)){holdPeriod = 801;} else if(spaceKey.downDuration(Phaser.Keyboard.SPACEBAR,1600)){holdPeriod = 1601;}

Also, you could re-write it cleaner like this:

var durations = [1, 800, 1600];var holdPeriod = 0;for(var v in durations) {   if(spaceKey.downDuration(Phaser.Keyboard.SPACEBAR, durations[v]) {       holdPeriod = durations[v];       break;   }}

Note that durations Array should be a static member, only created once.

Link to comment
Share on other sites


  • Recently Browsing   0 members

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