Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
How to make the balls move on canvas instead of manually moving on each click

I am working on a game where on each click on the canvas, the player (positioned on the canvas) shoots a ball in that direction. Right now what's working is that when ever I click on the canvas, it creates the ball and it advances as I keep clicking, but it should move forward automatically after the first click. I tried using requestAnimationFrame but I'm having scope issues.

This is the code that is relevant: The Game class:

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);
        }
             
         
   }
}

The Ball class:

    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(); 
        }
    }

What I tried to do was to move the animation part inside Game class so that I can call it using 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);
          }

        }
}

But that is not working as intended

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you define a function using the function keyword it will be defined in the global scope. If you want the function to use the Game instance as this, you can use an arrow function. Arrow functions bind the function's context to the context they are defined in.

Let's define a draw() method to the Game class.

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda