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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With