I'm trying to create multiple "bullets" in a shooting game.
For some reason I can only create one, I assume its because I am not properly creating more than one bullet object.
Below is my code I've used to produce the shooting feature. Can someone point me in the right direction on how I can recreate multiple bullets onclick?
bullet = {
x: null,
y: null,
width: 10,
height: 10,
direction: null,
update: function(){
if(this.direction == null){
if(lastKeyPress == null){
lastKeyPress = up;
}
this.direction = lastKeyPress;
}
if(this.direction == up){ this.y -=7; }
if(this.direction == down){ this.y +=7; }
if(this.direction == left){ this.x -=7; }
if(this.direction == right){ this.x +=7; }
},
draw: function() {
if(this.x == null){
this.x = player.x + (player.width/4);
}
if(this.y == null){
this.y = player.y + (player.height/4);
}
cContext.fillRect(this.x, this.y, this.width, this.height);
}
}
function main(){
canvas = document.getElementById("mainCanvas");
cContext = canvas.getContext("2d");
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
document.addEventListener("click", function(evt) {
bullets[bulletNum] = bullet;
bullets[bulletNum].draw();
bulletNum++;
});
init();
var loop = function(){
update();
draw();
window.requestAnimationFrame(loop, canvas);
}
window.requestAnimationFrame(loop, canvas);
}
function update() {
for (i = 0; i < bullets.length; i++) {
bullets[i].update();
}
player.update();
ai.update();
}
function draw() {
cContext.clearRect(0, 0, WIDTH, HEIGHT);
cContext.save();
for (i = 0; i < bullets.length; i++) {
bullets[i].draw();
}
player.draw();
ai.draw();
cContext.restore();
}
The issue is that once you shoot one bullet you cannot shoot after anymore.
I know there is alot of code here, any help would be fantastic.
bullets[bulletNum] = bullet;... always references same objectbulletNumis undefined actually. @Jon you are never creating different bullets anywhere. Please don't post questions with undefined variables.aiis also undefined. stackoverflow.com/help/how-to-ask and stackoverflow.com/help/mcve