Skip to content

Commit

Permalink
Merge pull request #302 from erf/simplify-gameloop
Browse files Browse the repository at this point in the history
Simplify GameLoop using a Ticker
  • Loading branch information
luanpotter authored May 7, 2020
2 parents 505a1ea + 95e3cce commit 669bbfc
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 28 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

## 0.20.0
- Refactor game.dart classes into separate files
- Split up gameloop into separate GameLoop class
- Adding a GameLoop class which uses a Ticker for updating game
- Adding sprites example
- Made BaseGame non-abstract and removed SimpleGame
- Adding SpriteButton Widget
Expand Down
39 changes: 14 additions & 25 deletions lib/game/game_loop.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,14 @@ import 'package:flutter/scheduler.dart';

class GameLoop {
Function callback;
int _frameCallbackId;
bool _running = false;
Duration previous = Duration.zero;
Ticker _ticker;

GameLoop(this.callback);

void scheduleTick() {
_running = true;
_frameCallbackId = SchedulerBinding.instance.scheduleFrameCallback(_tick);
}

void unscheduleTick() {
_running = false;
if (_frameCallbackId != null) {
SchedulerBinding.instance.cancelFrameCallbackWithId(_frameCallbackId);
}
GameLoop(this.callback) {
_ticker = Ticker(_tick);
}

void _tick(Duration timestamp) {
if (!_running) {
return;
}
scheduleTick();
final double dt = _computeDeltaT(timestamp);
callback(dt);
}
Expand All @@ -38,16 +23,20 @@ class GameLoop {
return delta.inMicroseconds / Duration.microsecondsPerSecond;
}

void start() {
_ticker.start();
}

void stop() {
_ticker.stop();
}

void pause() {
if (_running) {
previous = Duration.zero;
unscheduleTick();
}
_ticker.muted = true;
previous = Duration.zero;
}

void resume() {
if (!_running) {
scheduleTick();
}
_ticker.muted = false;
}
}
4 changes: 2 additions & 2 deletions lib/game/game_render_box.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class GameRenderBox extends RenderBox with WidgetsBindingObserver {
game.resumeEngineFn = gameLoop.resume;

if (game.runOnCreation) {
gameLoop.scheduleTick();
gameLoop.start();
}

_bindLifecycleListener();
Expand All @@ -45,7 +45,7 @@ class GameRenderBox extends RenderBox with WidgetsBindingObserver {
void detach() {
super.detach();
game.onDetach();
gameLoop.unscheduleTick();
gameLoop.stop();
_unbindLifecycleListener();
}

Expand Down

0 comments on commit 669bbfc

Please sign in to comment.