Math.abs in javascript

I am confused with math.abs (). I did research over the Internet, but could not find any relation to this animation with a rebound. I want to know how this works and how the ball jumps smoothly after using the 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 made a comment that confused me. Anyone please tell me how important this feature is for this animation.

Fiddle

+4
source share
2 answers

dx is the x offset.

Math.abs(dx) - absolute speed in x, that is, an unsigned value, always positive or zero.

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

could be written as

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

Basically, this line with the next stops the ball along x if it is already slow.

+14
source

dx decreases by 1% each time the last condition is satisfied ( if (y + dy > 290 || y + dy < 0) { )

this calculation can go on forever, but will lead to uneven results, since floating point accuracy errors will become a big factor compared to dx, so it’s better to stop the ball rebound when it is already slow, which is the test using Math-abs for you can 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

+2
source

All Articles