Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.abs in javascript

I am confused with math.abs(). I did Research through internet but couldn't find any relation with this bouncing ball's animation. I want to know how this works and how ball is bouncing smoothly after using math.abs() function?

function bounce() {
    if (x + dx > 293 || x + dx < 0) {
        dx = -dx;
    }
    if (y >= 290) {
        y = 290;
    }
    if (y + dy > 290 || y + dy < 0) {
        dx *= 0.99;
        dy = -dy;
    }
    //if (Math.abs(dx) < 0.01) {
       // dx = 0;
    }
    dy++;
}

I did comment the line confusing me. Anyone please let me know that how important this function for this animation.

Fiddle

like image 579
Manoz Avatar asked Dec 03 '22 00:12

Manoz


2 Answers

dx is the displacement on x.

Math.abs(dx) is the absolute speed on x, that is the value without the sign, always positive or null.

if (Math.abs(dx) < 0.01) {

could have been written as

if (dx>-0.01 && dx < 0.01) {

Basically, this line with the following one stops the ball along x if it's already slow.

like image 170
Denys Séguret Avatar answered Dec 05 '22 14:12

Denys Séguret


dx is reduced by 1% every time the last condition is met (if (y + dy > 290 || y + dy < 0) {)

this calculation can go on forever but would yield jagged results because the floating point precision errors would become a large factor compared to dx so better stop the ball bouncing when it is already slow which is what the test using Math-abs is for. In english you could read

if (Math.abs(dx) < 0.01) 

as if the speed of the ball in the x direction is less than 0.01 then stop the ball

like image 39
Rune FS Avatar answered Dec 05 '22 12:12

Rune FS