试图找出此请求动画帧函数中的变量"now"来自何处,或者如何动态获取其值



基本上我一直在尝试使用多个老虎机滚轮创建游戏。我已经尝试了许多版本来实现我的目标,并且都在PC上完美运行,但是一旦将它们放在移动设备上,它们就会滞后。这主要是因为我发现我在操纵 DOM 元素。

我在网上找到了一个功能,我已经复制了它并在应用程序中运行它,它运行得很好。

现在我尝试使用我自己的变量将此函数写入我的实际应用程序中。

我的问题是这样的:

有一个名为"NOW"的变量,它被传递给函数animate((;我试图弄清楚它来自哪里以及如何自己动态创建它。这个函数中有一个requestAnimationFrame请求,经过几个小时的研究,我仍然找不到任何东西。

这是代码所在的小提琴: https://codepen.io/indamix/pen/lLxcG

var sm = (function(undefined){
var tMax = 3000, 
height = 210,
speeds = [],
r = [],
reels = [
['coffee maker',   'teapot',       'espresso machine'],
['coffee filter',  'tea strainer', 'espresso tamper'],
['coffee grounds', 'loose tea',    'ground espresso beans']
],
$reels, 
$msg,
start;
function init(){
$reels = $('.reel').each(function(i, el){
el.innerHTML = '<div><p>' + reels[i].join('</p><p>') +   '</p></div><div><p>' + reels[i].join('</p><p>') + '</p></div>'
});
$msg = $('.msg');
$('button').click(action);
}
function action(){
if (start !== undefined) 
return;
for (var i = 0; i < 3; ++i) {
speeds[i] = Math.random() + .5; 
r[i] = (Math.random() * 3 | 0) * height / 3;
} 
$msg.html('Spinning...');
animate();
} 
function animate(now){  
if (!start) start = now;
var t = now - start || 0;
for (var i = 0; i < 3; ++i)
$reels[i].scrollTop = (speeds[i] / tMax / 2 * (tMax - t) *             (tMax - t) + r[i]) % height | 0;
if (t < tMax)
requestAnimationFrame(animate);
else {
start = undefined;
check();
}
}
function check(){
$msg.html(
r[0] === r[1] && r[1] === r[2] ?
'You won! Enjoy your ' + reels[1][ (r[0] / 70 + 1) % 3 | 0     ].split(' ')[0]  : 'Try again');}
return {init: init}
})();$(sm.init);

我已经在这里待了一段时间了,就像几天一样。我发现 Now 变量与 requestAnimationFrame 函数有关,用于确定动画帧的结束位置,但这对我来说只是猜测。我看不出来。

您可以使用performance.now()作为您自己的animate函数调用的参数值

相关内容

最新更新