Home>
I want to achieve

I want to stop the movement of the ball when it hits the wall twice.

I am currently creating a pinball game with JavaScript.
In the code below, clicking the "button" will fire a blue ball
The process is such that the ball stops when it hits the upper wall.

Stop the ball if it hits the wall twice, regardless of top, bottom, left or rightI would like to rewrite it as
I can't think of a good way.

We apologize for the inconvenience, but we would appreciate it if you could teach us.

let canvas = document.getElementById ("myCanvas");
let ctx = canvas.getContext ("2d");
let ballRadius = 15;
let x = canvas.width/2;
let y = canvas.height --15;
let dx = 2;
let dy = -2;
function drawBall () {
  ctx.beginPath ();
  ctx.arc (x, y, ballRadius, 0, Math.PI * 2);
  ctx.fillStyle = "# 0095DD";
  ctx.fill ();
  ctx.closePath ();
}

function draw () {
  ctx.clearRect (0, 0, canvas.width, canvas.height);
  drawBall ();
  if (x + dx>canvas.width --ballRadius || x + dx<ballRadius) {
    dx = -dx;
  }
  if (y + dy>canvas.height --ballRadius || y + dy<ballRadius) {
    dy = -dy;
  }
  x + = dx;
  y + = dy;
  if (y + dy == canvas.height --ballRadius --2 || y + dy == ballRadius --2) {
    dx = 0;
    dy = 0;
  }
}
draw ();
document.getElementById ("button"). onclick = function () {
  setInterval (draw, 10);
};

↓ Result

  • Answer # 1

    1) Add a variable declaration to hold the number of hits on the wall

    let dx = 2;
    let dy = -2;
    let cntBounce = 0;// Add this line


    2) Add a process to count up the variable in (1) when it hits a wall.

    if (x + dx>canvas.width --ballRadius || x + dx<ballRadius) {
        dx = -dx;
        cntBounce ++;// Add this line
      }
      if (y + dy>canvas.height --ballRadius || y + dy<ballRadius) {
        dy = -dy;
        cntBounce ++;// Add this line
      }


    3) Rewrite the ball stop condition to if the variable in (1) is 2 or more.

    // if (y + dy == canvas.height --ballRadius --2 || y + dy == ballRadius --2) {
      // dx = 0;
      // dy = 0;
      //}
      if (cntBounce>= 2) {// Rewrite like this
        dx = 0;
        dy = 0;
      }