Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I drive an animation loop at 60fps with Dart and the web?

Tags:

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

like image 652
Seth Ladd Avatar asked Apr 01 '13 22:04

Seth Ladd


1 Answers

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

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.

Here is a sample:

import 'dart:html';

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

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

The signature of animationFrame looks like:

Future<num> animationFrame();

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.

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.

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

like image 159
Seth Ladd Avatar answered Sep 18 '22 16:09

Seth Ladd