Home>

javascript ball stops after hitting the wall twice

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

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;
}
dy = -dy;
``````// if (y + dy == canvas.height --ballRadius --2 || y + dy == ballRadius --2) {