From 3a8e2464420f2b513f4f0d99cd7d64ab0eda9826 Mon Sep 17 00:00:00 2001 From: Kurtis Melby Date: Sat, 28 Oct 2023 19:19:36 -0400 Subject: [PATCH] fix: Setting world on FlameGame camera setter (#2831) # Description Currently setting a new `FlameGame.camera` can cause `camera.world` to no long match `game.world`, which I think it's safe to assume is never desirable. This PR sets the `camera.world` to the game's `world` when setting a new Camera, this matches what happens when a new World is set on the game (`world.camera` is set automatically). --- packages/flame/lib/src/game/flame_game.dart | 4 ++ packages/flame/test/game/flame_game_test.dart | 47 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/packages/flame/lib/src/game/flame_game.dart b/packages/flame/lib/src/game/flame_game.dart index b98d4e97f09..9f18fe460c5 100644 --- a/packages/flame/lib/src/game/flame_game.dart +++ b/packages/flame/lib/src/game/flame_game.dart @@ -65,6 +65,9 @@ class FlameGame extends ComponentTreeRoot /// /// You don't have to add the CameraComponent to the tree after setting it /// here, it is done automatically. + /// + /// When setting the camera, if it doesn't already have a world it will be + /// set to match the game's world. CameraComponent get camera => _camera; set camera(CameraComponent newCameraComponent) { _camera.removeFromParent(); @@ -72,6 +75,7 @@ class FlameGame extends ComponentTreeRoot if (_camera.parent == null) { add(_camera); } + _camera.world ??= world; } CameraComponent _camera; diff --git a/packages/flame/test/game/flame_game_test.dart b/packages/flame/test/game/flame_game_test.dart index d5564d9f9d7..188d07f3c5f 100644 --- a/packages/flame/test/game/flame_game_test.dart +++ b/packages/flame/test/game/flame_game_test.dart @@ -215,6 +215,53 @@ void main() { ); }, ); + + group('world and camera', () { + testWithFlameGame( + 'game world setter', + (game) async { + final newWorld = World(); + game.world = newWorld; + expect(game.world, newWorld); + expect(game.camera.world, newWorld); + }, + ); + + testWithFlameGame( + 'game camera setter', + (game) async { + final newCamera = CameraComponent(); + game.camera = newCamera; + expect(game.camera, newCamera); + expect(game.world, isNotNull); + expect(game.camera.world, game.world); + }, + ); + + testWithFlameGame( + 'game camera setter with another world', + (game) async { + final camera1 = game.camera; + final world1 = game.world; + expect(world1, isNotNull); + expect(camera1, isNotNull); + + final camera2 = CameraComponent(); + final world2 = World(); + camera2.world = world2; + + game.camera = camera2; + expect(game.camera, camera2); + expect(game.camera.world, world2); + expect(game.world, world1); + + game.camera = camera1; + expect(game.camera, camera1); + expect(game.camera.world, world1); + expect(game.world, world1); + }, + ); + }); }); group('Render box attachment', () {