在JavaScript中的Math.abs

时间:2013-02-07 11:36:49

标签: javascript jquery html canvas

我对math.abs()感到困惑。 我通过互联网进行了研究,但没有找到与这个弹跳球的动画有任何关系。我想知道这是如何工作的,以及在使用math.abs()函数后球是如何平滑弹跳的?

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++;
}

我做了评论让我感到困惑的一句话。任何人请告诉我这个动画对这个功能有多重要。

Fiddle

2 个答案:

答案 0 :(得分:14)

dx是x上的位移。

Math.abs(dx)是x上的绝对速度,即没有符号的值,始终为正或空。

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

本来可以写成

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

基本上,如果它已经很慢,那么这条带有以下一条的线会沿着x停止球。

答案 1 :(得分:3)

每次满足最后一个条件时,

dx减少1%(if (y + dy > 290 || y + dy < 0) {

这个计算可以永远进行,但会产生锯齿状结果,因为与dx相比,浮点精度误差会成为一个很大的因素,所以当它已经很慢时停止球弹跳这就是使用Math-abs进行的测试。用英语你可以阅读

if (Math.abs(dx) < 0.01) 

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