加权随机
通过为你选择的缓动曲线提供此函数,获得对你所选取数值的更多控制!
// reusable function. Feed in an array and an ease and it'll return
// a function that pulls a random element from that array, weighted
// according to the ease you provide.
function weightedRandom(collection, ease) {
return gsap.utils.pipe(
Math.random, //random number between 0 and 1
gsap.parseEase(ease), //apply the ease
gsap.utils.mapRange(0, 1, -0.5, collection.length-0.5), //map to the index range of the array, stretched by 0.5 each direction because we'll round and want to keep distribution (otherwise linear distribution would be center-weighted slightly)
gsap.utils.snap(1), //snap to the closest integer
i => collection[i] //return that element from the array
);
}
// usage:
var myArray = [0, 1, 2, 3],
getRandom = weightedRandom(myArray, "power4");
// now you can call it anytime and it'll pull a random element from myArray, weighted toward the end.
getRandom();
getRandom();
...
信息
如果想深入了解如何使用 weightedRandom 函数,请查看这个来自“GSAP 3:超越基础”课程的视频由 Snorkl.tv 制作——这是深入了解 GSAP 的最佳方式之一。