help to learn how to implement the shooting, as on this gif
could not find in google something worthwhile about this
var canvas = document.getElementById("d1"); var ctx = canvas.getContext("2d"); // ΠΊΠ½ΠΎΠΏΠΊΠΈ var pressedLeft = false; // Π»Π΅Π²ΠΎ var pressedRight = false; // ΠΏΡΠ°Π²ΠΎ var pressedSpace = false; // ΠΏΡΠΎΠ±Π΅Π» // ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΡ ΠΈΠ³ΡΠΎΠΊΠ° var playerWidth = 20; var playerHeight = 20; var playerX = (canvas.width - playerWidth)/2; var playerY = canvas.height - 25; //ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΡ ΠΏΡΠ»ΠΈ var bulletWidth = 5; var bulletHeight = 5; var bulletX = playerX; var bulletY = playerY; document.addEventListener("keydown", KeyDown, false); document.addEventListener("keyup", KeyUp, false); // ΠΊΠ½ΠΎΠΊΠ° Π½Π°ΠΆΠ°ΡΠ° function KeyDown(e) { if(e.keyCode == 37) { pressedLeft = true; } else if(e.keyCode == 39) { pressedRight = true; } else if(e.keyCode == 32) { pressedSpace = true; } } // ΠΊΠ½ΠΎΠΏΠΊΠ° Π½Π΅ Π½Π°ΠΆΠ°ΡΠ° function KeyUp(e) { if(e.keyCode == 37) { pressedLeft = false; } else if(e.keyCode == 39) { pressedRight = false; } else if(e.keyCode == 32) { pressedSpace = false; } } // ΡΠΈΡΡΠ΅ΠΌ ΠΈΠ³ΡΠΎΠΊΠ° function drawPlayer() { ctx.beginPath(); ctx.fillStyle = "black"; ctx.fillRect(playerX, playerY, playerWidth, playerHeight); ctx.fill(); ctx.closePath(); } // ΡΠΈΡΡΠ΅ΠΌ ΠΏΡΠ»Ρ function drawBullet() { ctx.beginPath(); ctx.fillStyle = "blue"; ctx.fillRect(playerX, playerY, bulletWidth, bulletHeight); // Π½Π΅ ΡΠ²Π΅ΡΠ΅Π½ ΡΡΠΎ ΡΡΠΎ ΠΏΡΠ°Π²ΠΈΠ»ΡΠ½Π°Ρ ΡΡΡΠΎΡΠΊΠ° ctx.fill(); ctx.closePath(); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawPlayer(); drawBullet(); if(pressedLeft && 0 < playerX) { playerX -= 5; } if(pressedRight && playerX < canvas.width - playerWidth) { playerX += 5; } } setInterval(draw, 10); #d1 { border: 1px solid black; } <canvas id="d1" width="250" height="250" ></canvas> Shooting should occur by pressing the spacebar.
Thank you in advance.
