Skip to content

Commit

Permalink
feat: Add pause and isPaused to SpriteAnimationTicker (#2660)
Browse files Browse the repository at this point in the history
Based on the Discord discussion and consultation with @ufrshubham, this PR adds the ability to pause a SpriteAnimationTicker.
  • Loading branch information
munsterlander authored Aug 20, 2023
1 parent f3d4158 commit 37271f5
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/flame/lib/src/sprite_animation_ticker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ class SpriteAnimationTicker {
/// still image).
bool get isSingleFrame => spriteAnimation.frames.length == 1;

bool _paused = false;

/// Returns current value of paused flag.
bool get isPaused => _paused;

/// Sets the given value of paused flag.
set paused(bool value) {
_paused = value;
}

/// A future that will complete when the animation completes.
///
/// An animation is considered to be completed if it reaches its [isLastFrame]
Expand All @@ -68,6 +78,7 @@ class SpriteAnimationTicker {
currentIndex = 0;
_done = false;
_started = false;
_paused = false;

// Reset completeCompleter if it's already completed
if (completeCompleter?.isCompleted ?? false) {
Expand Down Expand Up @@ -111,9 +122,12 @@ class SpriteAnimationTicker {
/// calls to [onStart].
bool _started = false;

/// Updates this animation, ticking the lifeTime by an amount [dt]
/// (in seconds).
/// Updates this animation, if not paused, ticking the lifeTime by an amount
/// [dt] (in seconds).
void update(double dt) {
if (_paused) {
return;
}
clock += dt;
elapsed += dt;
if (_done) {
Expand Down
21 changes: 21 additions & 0 deletions packages/flame/test/sprite_animation_ticker_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,26 @@ void main() {
animationTicker.completed;
expect(animationTicker.completeCompleter!.isCompleted, false);
});

test('paused pauses ticket', () async {
final sprite = MockSprite();
final animationTicker = SpriteAnimation.spriteList(
[sprite, sprite],
stepTime: 1,
loop: false,
).createTicker();

expect(animationTicker.isPaused, false);
expect(animationTicker.currentIndex, 0);
animationTicker.update(1);
expect(animationTicker.currentIndex, 1);
animationTicker.paused = true;
expect(animationTicker.isPaused, true);
animationTicker.update(1);
expect(animationTicker.currentIndex, 1);
animationTicker.reset();
expect(animationTicker.currentIndex, 0);
expect(animationTicker.isPaused, false);
});
});
}

0 comments on commit 37271f5

Please sign in to comment.