Skip to content

Commit

Permalink
fix: Setting world on FlameGame camera setter (#2831)
Browse files Browse the repository at this point in the history
# 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).
  • Loading branch information
kurtome committed Oct 28, 2023
1 parent fa9665a commit 3a8e246
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/flame/lib/src/game/flame_game.dart
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,17 @@ class FlameGame<W extends World> 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();
_camera = newCameraComponent;
if (_camera.parent == null) {
add(_camera);
}
_camera.world ??= world;
}

CameraComponent _camera;
Expand Down
47 changes: 47 additions & 0 deletions packages/flame/test/game/flame_game_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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', () {
Expand Down

0 comments on commit 3a8e246

Please sign in to comment.