Skip to content

Commit

Permalink
feat: Add a canSee method to the CameraComponent (#2270)
Browse files Browse the repository at this point in the history
Adding inView method so developers can more easily check if a given component is visible from a camera point of view.
  • Loading branch information
wolfenrain authored Jan 14, 2023
1 parent 6548e9c commit 2347c8f
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
13 changes: 13 additions & 0 deletions doc/flame/camera_component.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,19 @@ The `visibleWorldRect` is a cached property, and it updates automatically whenev
moves or the viewport changes its size.


### Check if a component is visible from the camera point of view

The `CameraComponent` has a method called `canSee` which can be used to check
if a component is visible from the camera point of view.
This is useful for example to cull components that are not in view.

```dart
if (!camera.canSee(component)) {
component.removeFromParent(); // Cull the component
}
```


## Comparison to the traditional camera

Compared to the normal [Camera](camera_and_viewport.md), the `CameraComponent`
Expand Down
5 changes: 5 additions & 0 deletions packages/flame/lib/src/camera/camera_component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -278,4 +278,9 @@ class CameraComponent extends Component {
boundedBehavior.bounds = bounds;
}
}

/// Returns true if this camera is able to see the [component].
bool canSee(PositionComponent component) {
return visibleWorldRect.overlaps(component.toAbsoluteRect());
}
}
34 changes: 34 additions & 0 deletions packages/flame/test/camera/camera_component_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,40 @@ void main() {
),
);
});

testWithFlameGame('component is in view for the camera', (game) async {
final world = World();
final camera = CameraComponent(
world: world,
viewport: FixedSizeViewport(60, 40),
);
game.addAll([world, camera]);
await game.ready();

final component = PositionComponent(
size: Vector2(10, 10),
position: Vector2(0, 0),
);

expect(camera.canSee(component), isTrue);
});

testWithFlameGame('component is out of view for the camera', (game) async {
final world = World();
final camera = CameraComponent(
world: world,
viewport: FixedSizeViewport(60, 40),
);
game.addAll([world, camera]);
await game.ready();

final component = PositionComponent(
size: Vector2(10, 10),
position: Vector2(100, 100),
);

expect(camera.canSee(component), isFalse);
});
});
}

Expand Down

0 comments on commit 2347c8f

Please sign in to comment.