From 619badd89fa75d51e235556d1f7efa824642813b Mon Sep 17 00:00:00 2001 From: alestiago Date: Wed, 16 Mar 2022 14:50:39 +0000 Subject: [PATCH] feat: included default value --- lib/game/components/initial_position.dart | 17 +++++++- .../components/initial_position_test.dart | 40 ++++++++++++++++--- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/lib/game/components/initial_position.dart b/lib/game/components/initial_position.dart index 61f19088..6b69af60 100644 --- a/lib/game/components/initial_position.dart +++ b/lib/game/components/initial_position.dart @@ -2,9 +2,24 @@ import 'package:flame_forge2d/flame_forge2d.dart'; /// Forces a given [BodyComponent] to position their [body] to an /// [initialPosition]. +/// +/// Note: If the [initialPosition] is set after the [BodyComponent] has been +/// loaded it will have no effect; defaulting to [Vector2.zero]. mixin InitialPosition on BodyComponent { + final Vector2 _initialPosition = Vector2.zero(); + + set initialPosition(Vector2 value) { + assert( + !isLoaded, + 'Cannot set initialPosition after component has been loaded.', + ); + if (value == initialPosition) return; + + _initialPosition.setFrom(value); + } + /// The initial position of the [body]. - late final Vector2 initialPosition; + Vector2 get initialPosition => _initialPosition; @override Future onLoad() async { diff --git a/test/game/components/initial_position_test.dart b/test/game/components/initial_position_test.dart index 4684ed71..1f5e0de7 100644 --- a/test/game/components/initial_position_test.dart +++ b/test/game/components/initial_position_test.dart @@ -28,11 +28,39 @@ void main() { ); }); - flameTester.test('positions correctly', (game) async { - final position = Vector2.all(10); - final component = TestBodyComponent()..initialPosition = position; - await game.ensureAdd(component); - expect(component.body.position, equals(position)); - }); + flameTester.test( + 'positions correctly', + (game) async { + final position = Vector2.all(10); + final component = TestBodyComponent()..initialPosition = position; + await game.ensureAdd(component); + expect(component.body.position, equals(position)); + }, + ); + + flameTester.test( + 'deafaults to zero ' + 'when no initialPosition is given', + (game) async { + final component = TestBodyComponent(); + await game.ensureAdd(component); + expect(component.body.position, equals(Vector2.zero())); + }, + ); + + flameTester.test( + 'setting throws AssertionError ' + 'when component has loaded', + (game) async { + final component = TestBodyComponent(); + await game.ensureAdd(component); + + expect(component.isLoaded, isTrue); + expect( + () => component.initialPosition = Vector2.all(4), + throwsAssertionError, + ); + }, + ); }); }