Why is my code not working when t is similar to MDN? (OOP)

This is MDN’s ball velocity code:

var ball = {
  x: 100,
  y: 100,
  vx: 5,
  vy: 2,
  radius: 25,
  color: 'blue',
  draw: function() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }
};

function draw() {
  ctx.clearRect(0,0, canvas.width, canvas.height);
  ball.draw();
  ball.x += ball.vx;
  ball.y += ball.vy;
  raf = window.requestAnimationFrame(draw);
};

canvas.addEventListener('mouseover', function(e){
  raf = window.requestAnimationFrame(draw);
});

ball.draw();

My code is here:

var Ball = function(x, y, vx, vy, r, color) {
  this.x = x;
  this.y = y;
  this.vx = vx;
  this.vy = vy;
  this.radius = r;
  this.color = color;
  this.draw = function() {
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fillStyle = color;
    ctx.fill();
  }
};

function movement() {
  pingPong.draw();
  pingPong.x += pingPong.vx;
  pingPong.y += pingPong.vy;
  raf = window.requestAnimationFrame(movement);
};

canvas.addEventListener('mouseover', function(e){
  raf = window.requestAnimationFrame(movement);
});

var pingPong = new Ball(100, 100, 5, 1, 15, 'black');

pingPong.draw();

I can’t understand why my ball isn’t being redrawn. To me they look exactly the same and I have console.log’d my x and y coordinates and they are updating as they should be. Can anyone tell me why mine isn’t working?


Source: oop

Leave a Reply