javascript 中的 Math.abs
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14750182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Math.abs in javascript
提问by Manoz
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?
我对 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++;
}
I did commentthe line confusing me. Anyone please let me know that how important this function for this animation.
我确实评论了让我困惑的行。任何人都请让我知道这个功能对这个动画有多重要。
Fiddle
小提琴
回答by Denys Séguret
dx
is the displacement on x.
dx
是 x 上的位移。
Math.abs(dx)
is the absolute speed on x, that is the value without the sign, always positive or null.
Math.abs(dx)
是 x 上的绝对速度,即不带符号的值,始终为正或为空。
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.
基本上,x
如果球已经很慢,这条线和以下一条线会停止球。
回答by Rune FS
dx is reduced by 1% every time the last condition is met (if (y + dy > 290 || y + dy < 0) {
)
每次满足最后一个条件时,dx 减少 1% ( 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
这种计算可以永远持续下去,但会产生参差不齐的结果,因为与 dx 相比,浮点精度误差将成为一个很大的因素,因此当球已经很慢时最好停止弹跳,这就是使用 Math-abs 的测试的目的。在英语中你可以阅读
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 the speed of the ball in the x direction is less than 0.01 then stop the ball