Skip to content
This repository has been archived by the owner on Mar 13, 2024. It is now read-only.

Commit

Permalink
feat: adjusted camera (#294)
Browse files Browse the repository at this point in the history
  • Loading branch information
alestiago authored Mar 11, 2024
1 parent 3bac9e2 commit f665fa3
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions packages/trashy_road/lib/src/game/game.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import 'package:flame/cache.dart';
import 'package:flame/camera.dart';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/experimental.dart';
import 'package:flame/game.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_tiled/flame_tiled.dart';
Expand Down Expand Up @@ -54,11 +55,20 @@ class TrashyRoadGame extends FlameGame

late final Player _player;

TrashyRoadWorld? _trashyRoadWorld;

@override
Color backgroundColor() {
return Colors.transparent;
}

@override
void onGameResize(Vector2 size) {
super.onGameResize(size);
_updateBounds();
_updateZoom();
}

@override
FutureOr<void> onLoad() async {
await super.onLoad();
Expand All @@ -68,7 +78,8 @@ class TrashyRoadGame extends FlameGame
GameSettings.gridDimensions,
);
final tiled = TiledComponent(renderableTiledMap);
final trashyRoadWorld = TrashyRoadWorld.create(tiled: tiled);
final trashyRoadWorld =
_trashyRoadWorld = TrashyRoadWorld.create(tiled: tiled);
children.register<TrashyRoadWorld>();

final blocProvider = FlameBlocProvider<GameBloc, GameState>(
Expand All @@ -85,15 +96,33 @@ class TrashyRoadGame extends FlameGame
world.add(blocProvider);

_player = trashyRoadWorld.tiled.children.whereType<Player>().first;
_player.children.register<PlayerDragMovingBehavior>();

camera.follow(_player);
_updateBounds();
}

@override
void onGameResize(Vector2 size) {
super.onGameResize(size);
void _updateBounds() {
final worldBounds = _trashyRoadWorld?.bounds;
if (worldBounds == null) return;

final viewportHalf = camera.viewport.size / 2;

final cameraBounds = Rectangle.fromPoints(
worldBounds.topLeft + viewportHalf,
worldBounds.bottomRight - viewportHalf,
);
camera.setBounds(cameraBounds);
}

void _updateZoom() {
final size = camera.viewport.size;
camera.viewfinder.zoom = (size.x / resolution.width) + 0.2;

final isPortrait = size.y > size.x;
if (isPortrait) {
// Increase the zoom on those mobile devices with a portrait aspect ratio
// to make the game look better, rather than too zoomed out.
camera.viewfinder.zoom += 0.4;
}
}

@override
Expand Down

0 comments on commit f665fa3

Please sign in to comment.