I'm creating a simple game in phaser, where I have a spaceship, which by pressing the space bar, shoots projectiles. This is the code:
var gameScene = new Phaser.Scene('game');
var navicella;
var bullets;
gameScene.preload = function(){
this.load.image('navicella', './assets/astronave.png')
this.load.image('bullet', './assets/bullet.png')
}
gameScene.create = function(){
navicella = this.physics.add.sprite(450, 500, 'navicella');
bullets = this.physics.add.group();
this.keySpace = this.input.keyboard.addKey(Phaser.Input.Keyboard.Key.SPACE, 100);
}
gameScene.update = function(){
navicella.x = this.input.mousePointer.x;
if(this.keySpace.isDown){
var bullet = bullets.create(navicella.x, 500, 'bullet');
bullet.setVelocityY(-100);
}
}
var config = {
type: Phaser.AUTO,
width: 900,
height: 600,
scene: gameScene,
physics: {
default: 'arcade',
arcade: {
debug: false,
gravity:{y: 0}
}
},
};
var game = new Phaser.Game(config);
The problem in the code, is that when I press the space bar, too many projectiles are generated, there is no limit. I had thought about adding a delay when projectiles spawn, but I have no idea how to do it.
The best way to achieve this with minimal effort is to use the keyboard events given by the phaser itself. So here is how you should implement keyboard events, instead of just checking if it is pressed, you should create an event listener and then write the logic inside.
You can create a keypressed event like this
Following are the keycodes, that you can use to trigger different buttons on the keyboard. KeyCodes
So, using this you can change your update function to something like this:
Let me know, if you require any resource for this, will be glad to help you out.