如何使用Dart驱动60fps的动画循环? [英] How do I drive an animation loop at 60fps with Dart?

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

问题描述

如何在Dart网络应用程序中以60fps驱动动画循环或游戏循环?

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

推荐答案

使用 window.animationFrame ,基于未来的传统 window.requestAnimationFrame 表哥。

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

Dart已转向使用未来 Stream 作为更多面向对象的方式来处理异步操作。基于回调的(old'n busted) 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.

未来在浏览器关于绘制页面之前就完成了。

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天全站免登陆