Why does this green ball get back in animation using this conditional?

2

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?

    
asked by anonymous 08.12.2017 / 22:58

1 answer

1

The value of the result dx = -dx; will be positive when dx is negative.

Why?

Assuming that dx is a negative number -10 , the expression would be:

dx = -(-10);

So, by the rule of mathematics, - with - results in a positive number, so:

dx = -10;
dx = -dx;
dx = -(-10);

dx = 10;

On the other hand, when dx is positive, then dx becomes negative:

dx = 10;
dx = -dx;
dx = -(10);

dx = -10;

Then, with each loop in the function, dx will change signal, and one of the conditions in if will be satisfied because it will influence the value of x . >     

08.12.2017 / 23:23