I'm coding a 2D sidescroller using only JavaScript and HTML5 canvas, and in my game I have two problems with shooting:
1) Player shoots continous stream of bullets. I want that player can shoot only a single bullet even though the shoot-button is being held down.
2) Also, I get an error "Uncaught TypeError: Cannot call method 'draw' of undefined" when all the bullets are removed. My shooting code goes like this: When player shoots, I do game.bullets.push(new Bullet(this, this.scale)); and after that:
function Bullet(source, dir)
{
this.id = "bullet";
this.width = 10;
this.height = 3;
this.dir = dir;
if (this.dir == 1)
{
this.x = source.x + source.width - 5;
this.y = source.y + 16;
}
if (this.dir == -1)
{
this.x = source.x;
this.y = source.y + 16;
}
}
Bullet.prototype.update = function()
{
if (this.dir == 1) this.x += 8;
if (this.dir == -1) this.x -= 8;
for (var i in game.enemies)
{
checkCollisions(this, game.enemies[i]);
}
// Check if bullet leaves the viewport
if (this.x < game.viewX * 32 || this.x > (game.viewX + game.tilesX) * 32)
{
removeFromList(game.bullets, this);
}
}
Bullet.prototype.draw = function()
{
// bullet flipping uses orientation of the player
var posX = game.player.scale == 1 ? this.x : (this.x + this.width) * -1;
game.ctx.scale(game.player.scale, 1);
game.ctx.drawImage(gameData.getGfx("bullet"), posX, this.y);
}
I handle removing with this function:
function removeFromList(list, object)
{
for (i in list)
{
if (object == list[i])
{
list.splice(i, 1);
break;
}
}
}
And finally, in the main game loop I have this:
for (var i in game.bullets)
{
game.bullets[i].update();
game.bullets[i].draw();
}
I have tried adding if (game.bullets.length > 0) to the main game loop before the above draw&update calls, but I still get the same error.