Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Cómo hacer que las bolas se muevan sobre el lienzo en lugar de moverlas manualmente con cada clic

Estoy trabajando en un juego en el que con cada clic en la lona, el jugador (posicionado en la lona) dispara una pelota en esa dirección. En este momento, lo que funciona es que cada vez que hago clic en el lienzo, crea la bola y avanza a medida que sigo haciendo clic, pero debería avanzar automáticamente después del primer clic. Intenté usar requestAnimationFrame pero tengo problemas de alcance.

Este es el código que es relevante: La clase Game :

 class Game { constructor(props) { // ... this.balls = [] this.canvas.addEventListener('mousedown', (e) => { this.handleMouseClicks(this.canvas, e) }); } handleMouseClicks(canvas, e) { if () { } else { this.balls.push(new Ball()); this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) // draw all the balls this.balls.forEach((ball) => { ball.animateBall(); }); // draw the player after clearing the canvas this.player.drawPlayer(this.playerPosX, this.playerPosY); } } }

La clase de Ball :

 class Ball { constructor(props) { // ... } updateBall() { this.ballPosX = this.ballPosX + this.velocity.x this.ballPosY = this.ballPosY + this.velocity.y } drawBall() { this.angle = Math.atan2(this.mouseClickPosY - this.cannonPosY, this.mouseClickPosX - this.cannonPosX); this.velocity = { x: Math.cos(this.angle), y: Math.sin(this.angle) }; this.ballRadius = 2; this.ctx.beginPath(); this.ctx.arc(this.ballPosX, this.ballPosY, this.ballRadius, 0, Math.PI * 2, false); this.ctx.closePath(); this.ctx.fillStyle = this.color; this.ctx.fill(); } animateBall() { this.drawBall(); this.updateBall(); } }

Lo que traté de hacer fue mover la parte de animación dentro de la clase Juego para poder llamarla usando requestAnimationFrame :

 handleMouseClicks(canvas, e) { if () { } else { loop(); function loop(){ this.balls.push(new Ball()); this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) // draw all the balls this.balls.forEach((ball) => { ball.animateBall(); }); // draw the player after clearing the canvas this.player.drawPlayer(this.playerPosX, this.playerPosY); requestAnimationFrame(loop); } } }

Pero eso no está funcionando según lo previsto.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Si define una función con la palabra clave function , se definirá en el ámbito global. Si desea que la función use la instancia del Juego como this , puede usar una función de flecha. Las funciones de flecha vinculan el contexto de la función al contexto en el que están definidas.

Definamos un método draw() para la clase Game .

 class Game { constructor() { // ... this.draw(); } // ... draw() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); // draw all the balls this.balls.forEach((ball) => { ball.animateBall(); }); // draw the player after clearing the canvas this.player.drawPlayer(this.playerPosX, this.playerPosY); // Here, "() => { /* function body */ }" is an arrow function example window.requestAnimationFrame(() => this.draw()); } }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda