Jump to content

call function once a second when key isDown()


Recommended Posts

So started learning Phaser today and I'm working on a very simple space shooter as a first project.

When i press the UP key i execute the shoot() function. But as this check is being done in the update loop, I shoot 60 times per second.

How can i solve this to let's say, shoot once a second or so.


This is my code:

function update(){    if(cursors.up.isDown)	    {	console.log('ispressed');	shoot();    }}function shoot(){    bullet = game.add.sprite(playerShip.x + 16, playerShip.y, 'bullet');    playerShip.bringToTop();    game.physics.arcade.enable(bullet);    bullet.body.velocity.y = -500;}

Also, how could i call shoot() once everytime i press the UP key, instead that i keep checking if the button is down.

Link to comment
Share on other sites

Modified your update function a bit, added a couple of variables, and came up with this (your shoot function remains the same):

var upKeyWasDown = false;var timeOfLastShot;function update(){    if (cursors.up.isDown && ((!upKeyWasDown) || (phaser.game.time.elapsedSecondsSince(timeOfLastShot) >= 1))) {        shoot();        timeOfLastShot = phaser.game.time.time;    }    upKeyWasDown = cursors.up.isDown;}

This fires a shot when one of the following conditions is met:

1) The up key is pressed currently and the up key wasn't pressed during the previous frame (this covers the shoot whenever the button is pressed requirement).

2) The up key is pressed currently, the up key was pressed during the previous frame (it is being held down), and at least one second has passed since the time of the last shot.


If one of these evaluates to true, then we call the shoot function, and record the time when the shot was made.


Finally, we record the up key's current state so that we can determine during the next frame if it's being held down or not.


Just a minor issue about this solution though, is that it uses the time property of a Phaser.Time object, which is marked in the documentation as internal. It should work with the current version of Phaser though as of the time when this post was written.

Link to comment
Share on other sites


  • Recently Browsing   0 members

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