javascript - unwanted multiple bullets in html shooter -
i trying create simple game paddle shoots single bullet. reason, each key press produces 2 bullets instead of intended one.
how can have single bullet firing delay of few seconds before next one?
i have set counter between each bullet, not working.
the code is:
/* canvas */ var canvas = document.getelementbyid("mycanvas"); var ctx = canvas.getcontext("2d"); /* input */ var rightpressed = false; var leftpressed = false; var spacepressed = false; document.addeventlistener("keydown", keydownhandler, false); document.addeventlistener("keyup", keyuphandler, false); function keydownhandler(e) { if(e.keycode == 39) { rightpressed = true; } else if(e.keycode == 37) { leftpressed = true; } else if(e.keycode == 32) { spacepressed = true; } } function keyuphandler(e) { if(e.keycode == 39) { rightpressed = false; } else if(e.keycode == 37) { leftpressed = false; } else if(e.keycode == 32) { spacepressed = false; } } /* paddle */ var paddle = { "height": 10, "width": 75, "paddlex": (canvas.width - 75)/2 } ; function drawpaddle() { if(rightpressed && paddle["paddlex"] < canvas.width - paddle["width"]) { paddle["paddlex"] = paddle["paddlex"] + 7; } else if(leftpressed && paddle["paddlex"] > 0) { paddle["paddlex"] = paddle["paddlex"] - 7; } ctx.beginpath(); ctx.rect(paddle["paddlex"], canvas.height - paddle["height"], paddle["width"], paddle["height"]); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); }; /* bullets */ var bullets = [] ; var bulletdelaycounter = 30; var bulletdelayincrement = 1; var bulletdelay = 30; function istriggerpressed() { if (spacepressed) { if (bulletdelaycounter > bulletdelay) { newbullet(paddle["paddlex"] + (paddle["width"] / 2)) bulletdelaycounter = 0 } } ; } ; function newbullet(x) { y = (canvas.height - paddle["height"]) - 2 bullets.push({ "y": y, "x": x }); } ; function drawbullet(x, y) { ctx.beginpath(); ctx.arc(x, y, 1, 0, math.pi*2); ctx.fillstyle = 'blue'; ctx.fill(); ctx.closepath(); } ; function animatebullets() { bulletdelaycounter = bulletdelaycounter + bulletdelayincrement; istriggerpressed(); (b of bullets) { drawbullet(b["x"], b["y"]) b["y"] = b["y"] - 4 } ; } ; /* game loop */ function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); drawpaddle(); animatebullets(); } ; setinterval(draw, 1);
Comments
Post a Comment