Estoy tratando de animar un círculo en movimiento de un lugar a otro. En el siguiente ejemplo, es de (10, 10) a (50, 50) A continuación se muestra el código de mi clase Bullet. Cuando el usuario hace clic en el espacio, creo un nuevo objeto Bullet y trato de animarlo. ¿Cómo puedo crear una animación fluida?
class Bullet{ constructor(x, y){ this.x = x; this.y = y; this.size = 10; } draw(){ ctx.fillStyle = "green"; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI) ctx.fill(); } fire(locationX, locationY){ } } document.addEventListener('keydown', function(e){ if(e.key == ' '){ var currBullet = new Bullet(10, 10); currBullet.fire(50, 50); } }); function reset(){ ctx.clearRect(0, 0, w, h); }Puede usar requestAnimationFrame para animar las viñetas. ¿Cuál es el objetivo general de esto? ¿Estás planeando disparar balas de (10, 10) a (50, 50)? ¿Es necesario limitar la distancia recorrida? ¿O lo disparará en una dirección basada en hacia dónde mira el jugador? ¿Quieres limitar el número de balas?
Este código hace lo que pediste pero es muy limitado.
const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); canvas.width = 200; canvas.height = 200; let bullets = []; class Bullet{ constructor(x, y){ this.x = x; this.y = y; this.size = 10; } draw(){ ctx.fillStyle = "green"; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI) ctx.fill(); } update(){ this.x += 1 this.y += 1 } } document.addEventListener('keydown', function(e){ if(e.code === 'Space'){ fire() } }); function fire() { bullets.push(new Bullet(10, 10)) } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (let i=0; i < bullets.length; i++) { bullets[i].draw() bullets[i].update() if (bullets[i].x >= 50 && bullets[i].y >= 50) { bullets.splice(i, 1) } } requestAnimationFrame(animate) } animate() <canvas id='canvas'></canvas>