From 516c9b3662b7e97c31828677abd91da17412a26a Mon Sep 17 00:00:00 2001 From: alestiago Date: Wed, 23 Mar 2022 09:45:40 +0000 Subject: [PATCH] feat: used a Timer in ChromeDino animation --- lib/game/components/chrome_dino.dart | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/lib/game/components/chrome_dino.dart b/lib/game/components/chrome_dino.dart index 620fe691..1ab2260b 100644 --- a/lib/game/components/chrome_dino.dart +++ b/lib/game/components/chrome_dino.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'dart:math' as math; -import 'package:flame_forge2d/flame_forge2d.dart'; +import 'package:flame_forge2d/flame_forge2d.dart' hide Timer; import 'package:flutter/material.dart'; import 'package:pinball/game/game.dart'; @@ -30,7 +30,7 @@ class ChromeDino extends BodyComponent with InitialPosition { anchor: anchor, ); final joint = _ChromeDinoJoint(jointDef)..create(world); - joint.swivel(joint, removed); + unawaited(removed.future.whenComplete(joint.dispose)); } // TODO(alestiago): Remove once the following is added to Flame. @@ -145,7 +145,14 @@ class _ChromeDinoAnchorRevoluteJointDef extends RevoluteJointDef { } class _ChromeDinoJoint extends RevoluteJoint { - _ChromeDinoJoint(_ChromeDinoAnchorRevoluteJointDef def) : super(def); + _ChromeDinoJoint(_ChromeDinoAnchorRevoluteJointDef def) : super(def) { + _timer = Timer.periodic( + const Duration(milliseconds: 100), + (_) => _swivel(), + ); + } + + late final Timer _timer; // TODO(alestiago): Remove once Forge2D supports custom joints. void create(World world) { @@ -155,14 +162,11 @@ class _ChromeDinoJoint extends RevoluteJoint { } /// Sweeps the [ChromeDino] up and down repeatedly. - void swivel(RevoluteJoint joint, Completer completer) { - Future.doWhile(() async { - if (completer.isCompleted) return false; - - // TODO(alestiago): Tune this values. - await Future.delayed(const Duration(milliseconds: 1000)); - joint.setMotorSpeed(-joint.motorSpeed); - return true; - }); + void _swivel() { + setMotorSpeed(-motorSpeed); + } + + void dispose() { + _timer.cancel(); } }