camera method to follow player
MODIFY
example/lib/player/knight.dart
example/lib/player/knight.dart
@@ -179,6 +179,7 @@ class Knight extends SimplePlayer with WithLighting {
void update(double dt) {
if (this.isDead || gameRef?.size == null) return;
_verifyStamina();
+ this.gameRef.gameCamera.moveToPlayer();
this.seeEnemy(
visionCells: 8,
notObserved: () {

MODIFY
lib/util/camera.dart
lib/util/camera.dart
@@ -156,10 +156,18 @@ class Camera with HasGameRef<RPGGame> {
);
}
- void moveToPlayer() {
- if (gameRef.player == null) return;
- Rect _positionPlayer = gameRef.player.position;
- moveToPosition(Position(_positionPlayer.left, _positionPlayer.top));
+ void moveToPlayer({double horizontal = 50, double vertical = 50}) {
+ if (gameRef?.player == null || gameRef?.size == null) return;
+ final screenCenter = Offset(gameRef.size.width / 2, gameRef.size.height / 2);
+ final positionPlayer = worldPositionToScreen(gameRef.player.position.center);
+ final horizontalDistance = screenCenter.dx - positionPlayer.dx;
+ final verticalDistance = screenCenter.dy - positionPlayer.dy;
+ if (horizontalDistance.abs() > horizontal) {
+ this.gameRef.gameCamera.position.x += horizontalDistance > 0 ? horizontal - horizontalDistance : -horizontalDistance - horizontal;
+ }
+ if (verticalDistance.abs() > vertical) {
+ this.gameRef.gameCamera.position.y += verticalDistance > 0 ? vertical - verticalDistance : -verticalDistance - vertical;
+ }
}
bool isComponentOnCamera(GameComponent c) {
@@ -167,4 +175,8 @@ class Camera with HasGameRef<RPGGame> {
return cameraRect.overlaps(c.position);
}
+
+ Offset worldPositionToScreen(Offset position) {
+ return position.translate(-gameRef.gameCamera.position.x, -gameRef.gameCamera.position.y);
+ }
}

MODIFY
lib/util/world_component.dart
lib/util/world_component.dart
@@ -28,13 +28,6 @@ abstract class WorldComponent extends GameComponent {
if (gameRef?.size == null || position == null || destroy() == true)
return false;
- final cameraRect = Rect.fromLTWH(
- gameRef.gameCamera.position.x,
- gameRef.gameCamera.position.y,
- gameRef.size.width,
- gameRef.size.height,
- );
-
- return position.overlaps(cameraRect);
+ return position.overlaps(gameRef.gameCamera.cameraRect);
}
}

camera method to follow player