52 lines
1.2 KiB
Dart
52 lines
1.2 KiB
Dart
import 'dart:html';
|
|
|
|
import 'package:browserloop/game/Game.dart';
|
|
import 'package:browserloop/game/LoopExample.dart';
|
|
|
|
/// The Variable Timestep Loop.
|
|
///
|
|
/// Perhaps one of the most widely used loops
|
|
/// in games for many years. Many game frameworks
|
|
/// make use of a loop similar to this.
|
|
class VariableTimestep implements LoopExample, VariableUpdates {
|
|
double _COLORSWITCHSPEED = 1.0;
|
|
Game game;
|
|
num id;
|
|
Stopwatch elapsed = new Stopwatch();
|
|
|
|
VariableTimestep(Game this.game);
|
|
|
|
void eventloop(num time) {
|
|
int dt = elapsed.elapsedMilliseconds;
|
|
|
|
// Multiply by dt, so that the color switching speed is the same,
|
|
// regardless of the time it took to compute this update
|
|
int colorSwitchspeed = (_COLORSWITCHSPEED / 10 * dt).toInt();
|
|
|
|
game.update(colorSwitchspeed);
|
|
game.draw();
|
|
elapsed.reset();
|
|
|
|
id = window.requestAnimationFrame(eventloop);
|
|
}
|
|
|
|
|
|
// CONTROLS ON THE EXAMPLE PAGE
|
|
// NOT NECESSARY FOR LOOP ITSELF
|
|
void stop() {
|
|
elapsed.stop();
|
|
window.cancelAnimationFrame(id);
|
|
}
|
|
|
|
void start() {
|
|
elapsed.start();
|
|
elapsed.reset();
|
|
window.requestAnimationFrame(eventloop);
|
|
}
|
|
|
|
@override
|
|
void setUpdates(double updateRate) {
|
|
_COLORSWITCHSPEED = 1000 / updateRate;
|
|
}
|
|
}
|