Skip to content

Commit e009ff1

Browse files
committed
feat: add TextBoxComponent::resetAnimation
Enables resetting of the typewriter animation of the TextBoxComponent. Useful for changing lines without having to re-insert the component into the scene node, which causes undesired flashing.
1 parent 79a5c20 commit e009ff1

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

packages/flame/lib/src/components/text_box_component.dart

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,4 +408,15 @@ class TextBoxComponent<T extends TextRenderer> extends TextComponent {
408408
void skip() {
409409
boxConfig = boxConfig.copyWith(timePerChar: 0);
410410
}
411+
412+
/// Rewind the typewriter effect to start from the first character again.
413+
///
414+
/// Useful for reusing this component when changing lines so that the next
415+
/// line does not show immediately.
416+
/// Also resets the [onComplete] call state which will be called again
417+
/// when the line is finished.
418+
void resetAnimation() {
419+
_lifeTime = 0;
420+
_isOnCompleteExecuted = false;
421+
}
411422
}

packages/flame/test/components/text_box_component_test.dart

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,35 @@ lines.''',
219219
expect(textBoxComponent2.finished, true);
220220
});
221221

222+
testWithFlameGame(
223+
'TextBoxComponent resets animation to the start of text',
224+
(
225+
game,
226+
) async {
227+
final textBoxComponent1 = TextBoxComponent(
228+
text: 'aaa',
229+
boxConfig: const TextBoxConfig(timePerChar: 1.0),
230+
);
231+
await game.ensureAdd(textBoxComponent1);
232+
// forward time by 2.5 seconds
233+
game.update(2.5);
234+
expect(textBoxComponent1.finished, false);
235+
// flush
236+
game.update(0.6);
237+
expect(textBoxComponent1.finished, true);
238+
// reset animation
239+
textBoxComponent1.resetAnimation();
240+
// 'finished' state should reset immediately
241+
expect(textBoxComponent1.finished, false);
242+
expect(textBoxComponent1.currentChar, 0);
243+
expect(textBoxComponent1.currentLine, 0);
244+
game.update(2.5);
245+
expect(textBoxComponent1.finished, false);
246+
game.update(0.6);
247+
expect(textBoxComponent1.finished, true);
248+
},
249+
);
250+
222251
testGolden(
223252
'Alignment options',
224253
(game, tester) async {

0 commit comments

Comments
 (0)