player.fire is a boolean value that turns true if the spacebar is in keydown. Everything works as it should.
The problem I have is controlling the array asteroids.firing.push interval. Right now, it adds a few instances, even when I tap lightly on the spacebar. I am using requestAnimationFrame.
How do I control the push interval?
if(player.fire){
var angle = thisShip.rot,
hyp = 10; //speed
var vX = Math.cos(angle) * hyp,
vY = Math.sin(angle) * hyp;
asteroids.firing.push(new asteroids.model.fire(thisShip.x, thisShip.y, vX, vY));
}
I have tried something like this, but it doesn’t slow down the push interval, rather it just creates a pulsing effect, regenerating the firing sequence again and again.
...
if(player.fire){
fireInterval(thisShip);
}
function fireInterval(thisShip){
var angle = thisShip.rot,
hyp = 10; //speed
var vX = Math.cos(angle) * hyp,
vY = Math.sin(angle) * hyp;
asteroids.firing.push(new asteroids.model.fire(thisShip.x, thisShip.y, vX, vY));
setTimeout(function(){
fireInterval(thisShip);
}, 500);
}
What’s happening is you’re calling this function every update.
I don’t know what your engine is like, but that might be up to 60fps if you’re using
requestAnimationFrame, or more if you’re just looping as quickly as possible, and updates aren’t tied to drawing.What you need to do is put some sort of state on the ship’s gun.
It doesn’t matter what it is…
Also, in terms of what the other people are suggesting:
I’m not sure how you’ve implemented listening to keyboard-events…
But handling keys in JS, what I’d be most-inclined to do is let the keyboard fire as many
keydownandkeyupevents as it wants.Instead of buffering that, have the only thing the key-event function does is tell a
Keyboardobject whether a key is down, or whether it is up.Poll that
Keyboardobject during your update.Poll to see if the key is down.
By setting the value of the key to
e.timeStamp, you now know when they started holding it down, so you can gate how often your ship fires.Better, you can set up a few abstracted systems, like:
Now you have something you can compare to your cooldown period and gates.
It won’t matter how fast they tap, or if keyboards work via turbo-fire by default, you should have all of the data-points required to prevent turbo-fire, to allow held-down auto-fire (gated at 250ms, or gated to having only 3 bullets onscreen, or whatever), and gated to a smaller value if you detect that the key keeps being tapped, to let button-mashers have a slight edge over button-holders.