Reputation: 2551
what i am trying to do basically is drawing and animating a bullet when the player hit the space bar .my problem the bullet is animating correctly but when you hold the space bar an infinite line of bullets is drawn this is a jsfiddle that can explain what i mean : http://jsfiddle.net/seekpunk/B2nUs/26/
the code :
var Missiles = {
collection: [],
draw: function () {
for (i = 0; i < this.collection.length; i++) {
this.collection[i].draw();
// Missiles.collection.length = 0;
}
},
update: function () {
if (Missiles.collection.length > 0) {
for (i = 0; i < Missiles.collection.length; i++) {
Missiles.collection[i].update();
// Missiles.collection.length = 0;
}
}
}
};
var playerMissile = function (M) {
Mx = this.x;
My = this.y;
MR = this.radius;
Msp = 3;
MDir = this.rot;
M.draw = function () {
ctx.fillStyle = "Green";
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
//this.h*2 specify that the image is in the row 2 of the tiled image
};
M.update = function () {
switch (this.rot) {
case 0: this.y -= 3; break;
case 90: this.x += 3; break;
case -90: this.x -= 3; break;
case 180: this.y += 3; break;
}
};
return M;
};
how can i make one bullet to be draw on each space bar hit even if the user hold down the space bar so i prevent this line of continuous bullets
Upvotes: 0
Views: 1436
Reputation: 19294
You need to handle an auto-fire by yourself.
Add two properties to your tank object
lastShootTime : 0, // time when we last shoot
shootRate : 300, // time between two bullets. (in ms)
Then, shoot only if enough time elapsed since last shoot :
shoot: function () {
var now = Date.now() ;
if (now - this.lastShootTime < this.shootRate) return;
this.lastShootTime = now ;
Missiles.collection.push(playerMissile({
x: this.x,
y: this.y,
radius: 2,
rot: this.rotation
}));
}
Rq1 : handle a speed for each missile, and have tank speed added to the missile to avoid the tank marching on its own missile (or speed the missile quite a bit for a quick fix. )
Rq 2 : you do not destroy missile when they are too far : do it.
Just an idea : you might improve the shootRate if the player gets an upgrade or so. You might also handle the heat of the canon, and have the shoot rate drop / stops on overheat.
I updated your fiddle, see here : http://jsfiddle.net/gamealchemist/B2nUs/27/
I also modified a few things, as you will see, so that the game is smooth and there's no blinking now.
( It works with requestAnimationFrame, i corrected a few var missing, update of tank is within the tank class, playerMissile is a proper class, and the update is time-based, so your game will behave the same on any device. )
Happy coding !!!
Upvotes: 4
Reputation: 881
try using a keyup event instead, as the keydown fires constantly and keyup fires once...
Upvotes: 0