我目前正在做一个 Js 动画。
让我解释一下:
我有几个对象,每个对象都有 Y 位置 this.y
。我想让它们像这样 this.y -= 0.1
向上移动,每个都有延迟。
问题:当对象从其原始位置向上移动 10px 时,我想将方向更改为向下(使用此代码 this.y += 0.1
)。当它从原来的位置移动 -10px 时,将方向更改为向上 (this.y -= 0.1
)。
这是一种循环值。任何想法 ?我想增加另一个变量,像这样:
this.incr = 0;
this.incr += 0.1;
if(this.incr == 1){
this.y += 0.1;
}
else if(this.incr == -1){
this.y -= 0.1;
}
我知道这不是好方法,但我找不到解决方案。
最佳答案
在您的对象中记录一个 delta
值,并使用它在每次调用时更新该值。如果达到限制,请更改 delta 的值。
myObject.update = function () {
this.value += this.delta
// if `this.value` reaches 1, the update function should subtract
// 0.1 on each subsequent call, so set `this.delta` to -0.1
if (this.value === 1)
this.delta = -0.1
// likewise, if `this.value` reaches -1, then the update function
// should add 0.1 on each call, so set `this.delta` to 0.1
else if (this.value === -1)
this.delta = +0.1
}
当然,这是您所追求的抽象。您将需要弄清楚如何翻译 this.value += this.delta
(即对象应该如何更新)以及何时切换 this.delta 的值
到您的应用程序中。
关于javascript - 如何做一个循环值javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41128405/