如何使用Dart和网络以60fps的速度驱动动画循环? [英] How do I drive an animation loop at 60fps with Dart and the web?

查看:80
本文介绍了如何使用Dart和网络以60fps的速度驱动动画循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Dart Web应用程序中以60fps的速度驱动动画循环或游戏循环?

How do I drive an animation loop or game loop at 60fps in a Dart web application?

推荐答案

使用 window.animationFrame ,传统 window.requestAnimationFrame 的基于Future的表亲。

Use window.animationFrame, the Future-based cousin of the traditional window.requestAnimationFrame.

Dart已转向使用未来是处理异步操作的更多面向对象的方法。基于回调的(旧有n个) requestAnimationFrame 被基于Future的(新功能) animationFrame 所代替。

Dart has been shifting to use Future and Stream as more object-oriented ways to handle asynchronous operations. The callback-based (old 'n busted) requestAnimationFrame is replaced by the Future-based (new hotness) animationFrame.

以下是示例:

import 'dart:html';

gameLoop(num delta) {
  // do stuff
  window.animationFrame.then(gameLoop);
}

void main() {
  window.animationFrame.then(gameLoop);
}

animationFrame 看起来像这样:

Future<num> animationFrame();

注意 animationFrame 如何返回完成的Future num ,其中包含一个类似于 window.performance.now()的高性能计时器。 num 是从现在到页面开始之间的单调递增的增量。它具有微秒级的分辨率。

Notice how animationFrame returns a Future that completes with a num, which holds a "high performance timer" similar to window.performance.now(). The num is a monotonically increasing delta between now and when the page started. It has microsecond resolution.

Future在浏览器即将绘制页面之前完成。更新世界的状态,并在此Future完成时绘制所有内容。

The Future completes right before the browser is about the draw the page. Update the state of your world and draw everything when this Future completes.

如果希望动画或循环继续进行,则必须在每帧上从animationFrame请求一个新的Future。 。在此示例中, gameLoop()注册以便在下一个动画帧上得到通知。

You must request a new Future from animationFrame on every frame, if you want the animation or loop to continue. In this example, gameLoop() registers to be notified on the next animation frame.

顺便说一句,有一个酒吧名为 game_loop 的软件包,您可能会发现它很有用。

BTW there is a pub package named game_loop, which you might find useful.

这篇关于如何使用Dart和网络以60fps的速度驱动动画循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆