Why is this little green ball able to rewind, in animation, using this conditional?

Asked

Viewed 33 times

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, do the opposite, 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 doubt is on that parole:

if (x + radius > window.innerWidth || x - radius < 0 ) {
    dx = -dx;
}

The first time the ball reaches the window boundary, the first conditional is used, causing the value of the várivel dx was negative, so the ball would start going backwards. Now when the ball reaches the other window boundary, the second conditional is used, running that code to leave the dx negative.
My question is, why, when the second parole is used, the ball can come back again, and the value of the variable dx It’s already negative, it wasn’t supposed to keep going on and on?

1 answer

1


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

Why?

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

dx = -(-10);

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

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

dx = 10;

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

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

dx = -10;

So every loop in function, the dx will change signal, and one of the conditions in the if will be met because it will influence the value of the x.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.