I have a javascript code that makes an animation of a green ball that moves until it reaches the limit of the width of the window, causing the ball to return, make the opposite way, until it reaches the other side of the window, and then come back again and so on.
var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext("2d");
var x = 200;
var dx = 10;
var radius = 30;
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
c.beginPath();
c.arc(x, 200, radius, 0, Math.PI * 2, false);
c.strokeStyle = "red";
c.fillStyle = "green";
c.stroke();
c.fill();
if (x + radius > window.innerWidth || x - radius < 0 ) {
dx = -dx;
}
x += dx;
};
animate();
My question is in this conditional:
if (x + radius > window.innerWidth || x - radius < 0 ) {
dx = -dx;
}
The first time the ball reaches the edge of the window, the first conditional is used, causing the value of the dx
variable to be negative, so that the ball begins to move backwards. Now when the ball reaches the other limit of the window, the second conditional is used, running that code to leave the dx
negative.
My question is, why, when the second conditional is used, does the ball get back again, since the value of the dx
is already negative, was it not to continue going on and on?