Actualmente mi sprite se está moviendo muy rápido. Espero ralentizarlo, como bajar el cuadro por segundo. He intentado usar setInterval() en varios lugares, pero ninguno parece funcionar.
Aquí está el código relevante:
class Atom { constructor(options){ this.width= 320; this.height= 320; this.frameX= 0; this.frameY= 0; this.pos= options.pos; this.game= options.game; this.img= new Image(); this.img.src = "sprite.png" this.img.onload = () => this.draw() } draw(ctx){ drawSprite(this.img, this.width * this.frameX, this.height * this.frameY, this.width, this.height,this.pos[0], this.pos[1], this.width, this.height); if (this.frameX < 20 ) { this.frameX++; } else { this.frameX= 0; }; } } function drawSprite(img, sX, sY, sW, sH, dX, dY, dW, dH) { ctx.drawImage(img, sX, sY, sW, sH, dX, dY, dW, dH); }esto se ejecutó en mi script.js:
//in game.js Game.prototype.draw= function(ctx) { ctx.clearRect(0, 0, Game.DIM_X, Game.DIM_Y); ctx.fillStyle = "rgba(0, 0, 0, 1)"; ctx.fillRect(0, 0, Game.DIM_X, Game.DIM_Y); this.atom.draw(ctx); } // in game_view.js GameView.prototype.start() { this.bindKeyHandlers(); this.lastTime = 0; // start the animation requestAnimationFrame(this.animate.bind(this)); } GameView.prototype.animate() { this.game.draw(this.ctx); requestAnimationFrame(this.animate.bind(this)); } // finally in index.js document.addEventListener("DOMContentLoaded", function(){ const canvas = document.getElementById('canvas'); canvas.width= Game.DIM_X; canvas.height= Game.DIM_Y; const ctx = canvas.getContext("2d"); const game= new Game(); game.draw(ctx); new GameView(game, ctx).start(); })Agradezco cualquier idea sobre cómo reducir la velocidad de fotogramas (para que la animación del sprite se ralentice) para un solo objeto. Espero evitar ralentizar la velocidad de animación del lienzo para que el sprite pueda moverse sin problemas.
Encontré una solución para esto:
//in class Atom constructor: this.counter = 3; //in class Atom's draw(ctx) function: if (this.counter > 0){ this.counter -=1; } else { if (this.frameX < 20 ) { this.frameX++; } else { this.frameX= 0; }; this.counter = 3 }Espero que esto te ahorre algo de tiempo, viajero cansado.