1. 소개
빌드할 항목
Flame은 Flutter 기반 2D 게임 엔진입니다. 이 Codelab에서는 1970년대 비디오 게임의 고전 중 하나인 스티브 워즈니악의 Breakout에서 영감을 받은 게임을 빌드합니다. Google Antigravity를 사용하여 에이전트에게 단계별로 프롬프트를 표시하여 배트, 공, 벽돌의 Flame Component를 빌드하고, Flame Effect로 배트의 움직임에 애니메이션을 적용하고, Flame을 Flutter의 상태 관리 시스템과 통합합니다.
완료되면 게임이 이 애니메이션 GIF와 같이 표시됩니다. 단, 약간 느립니다.

완성된 게임은 다음 요구사항을 충족합니다.
- Flutter가 지원하는 6가지 플랫폼(Android, iOS, Linux, macOS, Windows, 웹)에서 작동합니다.
- Flame의 게임 루프를 사용하여 최소 60fps를 유지합니다.
google_fonts및flutter_animate와 같은 Flutter 패키지를 사용하여 70년대와 80년대의 아케이드 게임 느낌을 재현합니다.
학습 여정
이 Codelab에서는 게임을 단계별로 빌드하는 과정을 안내합니다.
- Flutter 환경 설정 - 대상 플랫폼에 맞게 Flutter 및 Google Antigravity를 구성합니다.
- 프로젝트 만들기 - Antigravity에 Flame,
flutter_animate,google_fonts,material_ui를 사용하여 빈 Flutter 프로젝트를 스캐폴딩하라는 프롬프트를 표시합니다. - 게임 만들기 - 고정 해상도 카메라를 구성하고 게임 세계에
PlayArea구성요소를 추가합니다. - 공 표시 - Flame의 게임 루프와 속도 벡터로 구동되는 움직이는
Ball구성요소를 추가합니다. - Bounce around - 충돌 감지 및 히트박스를 사용 설정하여 공이 벽에 부딪혀 튕겨 나가도록 합니다.
- 배트로 공 치기 -
MoveToEffect를 사용하여 드래그 및 키보드 입력을 지원하는 플레이어 제어Bat를 추가합니다. - Break down the wall -
Brick구성요소 그리드를 생성하고 벽돌이 깨질 때 공의 속도를 조정합니다. - 게임 승리 -
GameWidget.controlled를 사용하여 게임 상태를 관리하고 복고풍 Flutter 위젯 오버레이를 표시합니다. - 점수 기록 -
ValueNotifier를 사용하여 플레이어의 점수를 Flutter UI와 동기화하고flutter_animate를 사용하여 오버레이를 애니메이션 처리합니다.
학습할 내용
- Google Antigravity와 협업하여 Flame 게임을 반복적으로 빌드하고 맞춤설정하는 방법
GameWidget부터 시작하는 Flame의 기본 작동 방식- 프레임 속도 독립적 움직임을 위해 게임 루프를 사용하는 방법
- Flame의
Component작동 방식(Flutter의Widget와 유사) - 히트박스를 사용하여 충돌을 감지하고 대응하는 방법
Effect를 사용하여Component에 애니메이션을 적용하고 삭제하는 방법- Flame 게임 위에 Flutter
Widget를 오버레이하는 방법 - Flame을 Flutter의 상태 관리와 통합하는 방법
기본 요건
- Flutter 및 Dart 문법에 관한 기본 지식
2. Flutter 환경 설정
편집자
이 Codelab에서는 Google Antigravity를 AI 우선 개발 환경으로 사용합니다. 각 단계에서 Antigravity에 프롬프트를 입력하여 게임 구성요소를 생성하거나 발전시키고, 생성된 코드에서 주요 Flame 개념을 검토하고, 원하는 경우 시대에서 영감을 받은 아케이드 변형을 살펴봅니다.
개발 타겟 선택
Flutter는 여러 플랫폼용 앱을 생성합니다. 앱이 다음 운영체제 어디서든 실행될 수 있습니다.
- iOS
- Android
- Windows
- macOS
- Linux
- 웹
하나의 운영체제를 개발 타겟으로 선택하는 것이 일반적입니다. 개발하는 동안 앱을 실행할 운영체제입니다.

예를 들어 Windows 노트북을 사용하여 Flutter 앱을 개발한다고 가정해 보겠습니다. Android를 개발 타겟으로 선택하면 USB 케이블을 통해 Android 기기를 Windows 노트북에 연결하고 개발 중인 앱은 연결된 Android 기기(또는 Android Emulator)에서 실행됩니다. 또는 개발 타겟으로 Windows를 선택할 수도 있습니다. 이 경우 개발 중인 앱이 편집기와 함께 데스크톱 Windows 앱으로 실행됩니다.
계속하기 전에 선택하세요. 나중에 언제든지 다른 운영체제에서 앱을 실행할 수 있습니다. 개발 타겟을 선택하면 다음 단계를 원활하게 진행할 수 있습니다.
Flutter 설치
Flutter SDK 설치에 관한 가장 최신 안내는 docs.flutter.dev에서 항상 확인할 수 있습니다.
Flutter 웹사이트에서는 SDK, 플랫폼별 도구, 편집기 플러그인 설치에 관해 안내합니다. 이 Codelab에서는 다음 소프트웨어를 설치합니다.
- Flutter SDK
- 공식 Dart 및 Flutter 플러그인이 사용 설정된 Google Antigravity(플러그인 마켓플레이스의 Build with Google 섹션에서 사용 가능)
- 선택한 개발 타겟의 컴파일러 소프트웨어(예: Windows를 타겟팅하는 Visual Studio, macOS 또는 iOS를 타겟팅하는 Xcode)
다음 단계에서는 Antigravity에 Flutter 프로젝트를 만들고 초기 Flame 게임을 스캐폴딩하라는 프롬프트를 표시합니다.
문제 해결
설정 문제가 발생하면 다음 Stack Overflow 질문 및 답변이 도움이 될 수 있습니다.
- Flutter SDK 경로는 어떻게 찾을 수 있나요?
- Flutter 명령어를 찾을 수 없으면 어떻게 해야 하나요?
- '시작 잠금을 해제하기 위해 다른 Flutter 명령어를 기다리는 중' 문제를 해결하려면 어떻게 해야 하나요?
- Flutter에 Android SDK 설치 위치를 알리려면 어떻게 해야 하나요?
flutter doctor --android-licenses를 실행할 때 Java 오류를 처리하려면 어떻게 해야 하나요?- 찾을 수 없는 Android
sdkmanager도구는 어떻게 처리해야 하나요? - '
cmdline-tools구성요소가 누락됨' 오류는 어떻게 처리해야 하나요? - Apple Silicon(M1)에서 CocoaPods를 실행하려면 어떻게 해야 하나요?
3. 프로젝트 만들기
Antigravity에 프로젝트를 만들라는 프롬프트 입력
- Google Antigravity를 실행하고 게임을 빌드할 빈 디렉터리를 엽니다(홈 디렉터리의 폴더 또는
C:\src\와 같이 승격된 권한이 필요하지 않거나 공백이 포함되지 않은 경로를 선택). - Antigravity 에이전트 채팅 패널에서 다음 프롬프트를 전송하여 Flutter 프로젝트를 만들고, 종속 항목을 추가하고, 최소한의 Flame 게임을 연결합니다.
Create a new empty Flutter project named `brick_breaker` for a Breakout-style 2D arcade game. Add the `flame`, `flutter_animate`, `google_fonts`, and `material_ui` packages, and update `lib/main.dart` (importing `package:flame/game.dart` and `package:material_ui/material_ui.dart`) to run a basic `FlameGame` inside a `GameWidget`.
생성된 코드 이해
Antigravity는 flutter create --empty를 실행하여 프로젝트를 스캐폴드하고, flame, flutter_animate, google_fonts, material_ui를 pubspec.yaml에 추가하고, lib/main.dart를 업데이트하여 Flutter의 GameWidget 내에서 FlameGame 인스턴스를 호스팅합니다.
void main() {
final game = FlameGame();
runApp(GameWidget(game: game));
}
게임 실행 및 테스트
선택한 개발 타겟에서 앱을 실행하여 모든 것이 제대로 작동하는지 확인합니다. 검은색 배경의 새 창이 표시됩니다. 세계에서 가장 간단한 비디오 게임이 이제 60fps로 렌더링됩니다.

4. 게임 만들기
게임 크기 측정
2차원(2D)으로 플레이하는 게임에는 플레이 영역이 필요합니다. 이 단계에서는 특정 크기의 플레이 영역을 구성하고 이 크기를 사용하여 나머지 게임 구성요소의 크기를 조정합니다.
플레이 영역에 좌표를 배치하는 방법은 다양합니다. 한 가지 규칙에 따라 화면 중앙에서 원점 (0,0)을 중앙에 두고 방향을 측정합니다. 여기서 양수 값은 항목을 x축을 따라 오른쪽으로, y축을 따라 위로 이동합니다. 이 표준은 최신 3D 게임 엔진에서 일반적입니다.
원래 Breakout 게임이 만들어졌을 때는 원점을 왼쪽 상단에 배치하는 것이 관례였습니다. 양의 x 방향은 오른쪽을 가리키고 양의 y 방향은 아래쪽을 가리킵니다. 이 게임은 당시의 느낌을 살리기 위해 원점을 왼쪽 상단으로 설정합니다.
Antigravity에 게임 및 PlayArea를 만들라는 프롬프트 입력
Antigravity에서 다음 프롬프트를 전송하여 고정 해상도 게임 세계와 플레이 영역을 설정합니다.
Create a `BrickBreaker` subclass of `FlameGame` in `lib/src/brick_breaker.dart` with a fixed-resolution camera (820x1600, defined in `lib/src/config.dart`) anchored at the top-left corner. Add a `PlayArea` rectangle component (`lib/src/components/play_area.dart`, re-exported in `lib/src/components/components.dart`) that fills the game's width and height with a warm arcade background color (`0xfff2e8cf`), and wire `BrickBreaker` up in `lib/main.dart`.
생성된 코드 이해
PlayArea 및 Flame Component
Flutter에는 Widget가 있고 Flame에는 Component가 있습니다. Flutter 앱은 위젯 트리로 구성되지만 Flame 게임은 구성요소 트리를 유지합니다.
Flutter의 위젯 트리는 영구적이고 변경 가능한 RenderObject 레이어를 업데이트하는 데 사용되는 변경 불가능한 설명입니다. Flame의 구성요소는 영구적이고 변경 가능하며 lib/src/components/play_area.dart의 시뮬레이션 시스템의 일부로 직접 사용하도록 설계되었습니다.
class PlayArea extends RectangleComponent with HasGameReference<BrickBreaker> {
PlayArea() : super(paint: Paint()..color = const Color(0xfff2e8cf));
@override
FutureOr<void> onLoad() async {
super.onLoad();
size = Vector2(game.width, game.height);
}
}
구성요소를 추가할 때 가져오기 혼란을 제어하기 위해 lib/src/components/components.dart는 export 지시어를 사용하여 단일 배럴 파일에서 모든 구성요소를 다시 내보냅니다.
고정 해상도 카메라 및 world
lib/src/brick_breaker.dart에서 BrickBreaker는 고정 820x1600 해상도를 사용하도록 게임을 구성합니다.
class BrickBreaker extends FlameGame {
BrickBreaker()
: super(
camera: CameraComponent.withFixedResolution(
width: gameWidth,
height: gameHeight,
),
);
@override
FutureOr<void> onLoad() async {
super.onLoad();
camera.viewfinder.anchor = Anchor.topLeft;
world.add(PlayArea());
}
}
게임은 게임이 포함된 창을 채우도록 크기가 조절되고 필요에 따라 레터박스를 추가합니다.
onLoad에서 코드는 두 가지 주요 작업을 실행합니다.
- 왼쪽 상단 모서리를
viewfinder의 앵커로 구성합니다(기본값은 영역의 중심인(0,0)). world에PlayArea를 추가합니다. 그러면CameraComponent의 뷰 변환을 통해 모든 하위 요소가 투영됩니다.
게임 실행 및 테스트
핫 리스타트(또는 전체 다시 시작)를 실행하여 변경사항을 확인합니다.

다음 단계에서는 월드에 공을 추가하고 움직이게 합니다.
5. 공 표시
Antigravity에 Ball 구성요소를 추가하라는 프롬프트 입력
화면에 움직이는 공을 배치하려면 Ball 구성요소를 정의하고 게임 세계에 추가해야 합니다. Antigravity에서 다음 프롬프트를 전송합니다.
Add a `Ball` circle component (`lib/src/components/ball.dart`) with a radius of 2% of the game width and a velocity vector that updates the ball's position each frame (`position += velocity * dt`). Spawn the ball at the center of the play area in `BrickBreaker.onLoad()` moving downward in a randomized direction at a consistent speed (scaled to a quarter of the game height), and enable `debugMode = true` so we can see component bounds.
생성된 코드 이해
파생 구성 상수
lib/src/config.dart의 ballRadius = gameWidth * 0.02를 파생 상수로 정의하면 최상위 수준의 gameWidth 및 gameHeight를 수정하여 게임의 디자인과 분위기가 어떻게 달라지는지 살펴볼 수 있습니다.
Ball의 프레임 속도 독립 모션
CircleComponent는 RectangleComponent와 마찬가지로 PositionComponent에서 파생되므로 position는 lib/src/components/ball.dart의 모든 프레임에서 업데이트할 수 있습니다.
final Vector2 velocity;
@override
void update(double dt) {
super.update(dt);
position += velocity * dt;
}
속도는 Vector2 객체입니다. 속도에는 속력과 방향이 모두 있기 때문입니다. Flame은 프레임마다 update를 호출하여 dt(이전 프레임 이후의 델타 시간(초))를 전달합니다. velocity * dt를 곱하면 다양한 화면 재생 빈도(예: 60Hz와 120Hz)에서 시뮬레이션 속도가 일정하게 유지됩니다.
초기 속도 정규화
lib/src/brick_breaker.dart에서 공은 중앙(size / 2)에서 무작위 하향 속도로 시작합니다.
world.add(
Ball(
radius: ballRadius,
position: size / 2,
velocity: Vector2(
(rand.nextDouble() - 0.5) * width,
height * 0.2,
).normalized()..scale(height / 4),
),
);
normalized()를 호출하면 동일한 무작위 방향을 가리키는 단위 벡터(길이 1)가 생성되고 ..scale(height / 4)는 각도에 관계없이 공이 항상 동일한 속도로 시작하도록 크기를 조정합니다.
게임 실행 및 테스트
게임을 핫 리스타트합니다. debugMode = true를 사용 설정하면 Flame은 구성요소 트리에 보라색 경계 상자와 좌표를 표시합니다.

게임을 몇 번 다시 시작하면 공이 플레이 영역의 가장자리를 통과하는 것을 확인할 수 있습니다. 이 문제를 해결하기 위해 다음 단계에서 충돌 감지를 추가합니다.
6. 통통 튀기기
Antigravity에 충돌 감지를 추가하라는 프롬프트 입력
충돌 감지를 사용하면 게임에서 두 구성요소가 접촉하는 시점을 인식할 수 있습니다. Antigravity에서 다음 프롬프트를 전송합니다.
Enable collision detection on `BrickBreaker` and add hitboxes to `PlayArea` and `Ball`. In `Ball.onCollisionStart`, bounce the ball off the top, left, and right walls of `PlayArea` by reversing the appropriate velocity axis, and remove the ball when it hits the bottom edge.
생성된 코드 이해
히트박스 및 HasCollisionDetection
BrickBreaker에 HasCollisionDetection 믹스인을 추가하면 구성요소 히트박스(PlayArea의 RectangleHitbox 및 Ball의 CircleHitbox)를 추적하고 모든 게임 틱에서 충돌 콜백을 트리거합니다.
Ball에서 벽 충돌 처리
lib/src/components/ball.dart에서 onCollisionStart는 공이 상단, 왼쪽 또는 오른쪽 벽에 부딪힐 때 공의 속도 벡터를 반영하고 하단에 부딪힐 때 공을 삭제합니다.
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
super.onCollisionStart(intersectionPoints, other);
if (other is PlayArea) {
if (intersectionPoints.first.y <= 0) {
velocity.y = -velocity.y;
} else if (intersectionPoints.first.x <= 0) {
velocity.x = -velocity.x;
} else if (intersectionPoints.first.x >= game.width) {
velocity.x = -velocity.x;
} else if (intersectionPoints.first.y >= game.height) {
removeFromParent();
}
} else {
debugPrint('collision with $other');
}
}
게임 실행 및 테스트
게임을 핫 리스타트합니다. 공이 PlayArea의 왼쪽 및 오른쪽 벽에 부딪혀 튕겨 나가고 하단 가장자리에 도달하면 사라지는 것을 확인합니다.
이제 공이 벽에 부딪혀 튕겨 나가므로 플레이어에게 공을 다시 위로 칠 수 있는 배트를 제공합니다.
7. 배트로 공을 치세요
Antigravity에 Bat 구성요소를 추가하라는 프롬프트 입력
Antigravity에서 다음 프롬프트를 전송하여 플레이어가 제어하는 Bat 구성요소를 만들고 배트와 공의 충돌을 처리합니다.
Add a player-controlled `Bat` component (`lib/src/components/bat.dart`) positioned near the bottom of the play area (`height * 0.95`). Render it as a rounded rectangle with a `RectangleHitbox`, and let the player move it horizontally both by dragging (`DragCallbacks`) and with the left and right arrow keys (`KeyboardEvents` on `BrickBreaker` using a short `MoveToEffect`). In `Ball`, replace immediate bottom removal with a delayed `RemoveEffect(delay: 0.35)`, and when the ball hits the `Bat`, reverse its vertical velocity and deflect its horizontal velocity based on how far from the bat's center the ball struck.
생성된 코드 이해
Bat의 맞춤 렌더링, 드래그, MoveToEffect
PlayArea 및 Ball와 달리 lib/src/components/bat.dart의 Bat는 PositionComponent를 직접 확장하고 render를 재정의하여 둥근 직사각형(RRect)을 그립니다.
@override
void render(Canvas canvas) {
super.render(canvas);
canvas.drawRRect(
RRect.fromRectAndRadius(Offset.zero & size.toSize(), cornerRadius),
_paint,
);
}
Offset.zero & size.toSize()는 Offset 및 Size에서 & 연산자를 사용하여 Rect를 구성합니다.
입력의 경우 Bat은 두 가지 형식을 지원합니다.
DragCallbacks및onDragUpdate를 사용한 마우스 및 터치 드래그moveBy(double dx)를 사용한 키보드 이동. FlameMoveToEffect를 연결하여 100ms 동안 배트를 부드럽게 애니메이션화합니다.
void moveBy(double dx) {
add(
MoveToEffect(
Vector2((position.x + dx).clamp(0, game.width), position.y),
EffectController(duration: 0.1),
),
);
}
Ball에서 지연된 삭제 및 각진 배트 바운스
lib/src/components/ball.dart에서는 두 가지 개선사항을 통해 공 상호작용이 훨씬 더 자연스럽게 느껴집니다.
removeFromParent()를add(RemoveEffect(delay: 0.35))로 바꾸면 공이 하단 가장자리를 지나 사라집니다.Bat와 충돌할 때velocity.x는 배트 중심을 기준으로 공이 배트에 부딪힌 위치에 따라 조정됩니다.
} else if (other is Bat) {
velocity.y = -velocity.y;
velocity.x =
velocity.x +
(position.x - other.position.x) / other.size.x * game.width * 0.3;
}
게임 실행 및 테스트
게임을 핫 리스타트합니다. 마우스나 손가락으로 드래그하거나 왼쪽 및 오른쪽 화살표 키를 눌러 배트를 움직이고 공을 화면 상단으로 다시 튕깁니다.
이제 공을 칠 배트가 있으니 부술 벽돌 벽을 추가합니다.
8. 벽 허물기
Antigravity에 Bricks를 추가하라는 프롬프트
Antigravity에서 다음 프롬프트를 전송하여 Brick 구성요소를 만들고, 벽돌 그리드를 배치하고, 벽돌이 깨질 때 공의 속도를 높입니다.
Create a `Brick` rectangle component (`lib/src/components/brick.dart`) with a hitbox and add a 10-column by 5-row grid of colored bricks across the top of the play area using constants in `lib/src/config.dart`. When the ball collides with a brick, remove the brick, reflect the ball's velocity off the side of the brick it hit, and multiply the ball's velocity by a `difficultyModifier` (such as `1.03`) so the game speeds up. When the last brick is destroyed, remove the ball and bat from the world.
생성된 코드 이해
구성요소 삭제 및 승리 확인을 대기열에 추가
lib/src/components/brick.dart에서 Brick.onCollisionStart는 벽돌을 삭제하고 월드의 마지막 벽돌인지 확인합니다.
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
super.onCollisionStart(intersectionPoints, other);
removeFromParent();
if (game.world.children.query<Brick>().length == 1) {
game.world.removeAll(game.world.children.query<Ball>());
game.world.removeAll(game.world.children.query<Bat>());
}
}
removeFromParent()를 호출한 후 검사에서 query를 비교하는 이유는 무엇인가요? Flame에서 구성요소 삭제는 대기열에 추가된 명령어이기 때문입니다. 브릭은 현재 콜백이 완료된 후 다음 게임 틱 전에 구성요소 트리에서 삭제됩니다.
Ball의 난이도 곡선
Ball가 lib/src/components/ball.dart의 Brick와 충돌하면 적절한 속도 축을 반영하고 속도 벡터에 difficultyModifier(1.03)를 곱하여 벽돌이 깨질 때마다 공의 속도를 점진적으로 높입니다.
} else if (other is Brick) {
if (position.y < other.position.y - other.size.y / 2) {
velocity.y = -velocity.y;
} else if (position.y > other.position.y + other.size.y / 2) {
velocity.y = -velocity.y;
} else if (position.x < other.position.x) {
velocity.x = -velocity.x;
} else if (position.x > other.position.x) {
velocity.x = -velocity.x;
}
velocity.setFrom(velocity * difficultyModifier);
}
게임 실행 및 테스트
게임을 핫 리스타트하여 전체 벽돌 벽을 확인합니다.

다음으로 Flutter 위젯을 사용하여 시작, 게임 오버, 승리 오버레이를 추가합니다.
9. 게임에서 승리하기
Antigravity에 PlayState 및 Flutter 오버레이를 추가하라는 프롬프트 입력
이 단계에서는 PlayState enum을 도입하고, 오버레이가 있는 스타일이 지정된 Flutter GameApp 위젯 내에 Flame 게임을 삽입하고, google_fonts의 플랫폼 네트워크 권한을 구성합니다. Antigravity에서 다음 프롬프트를 전송합니다.
Add a `PlayState` enum (`welcome`, `playing`, `gameOver`, `won`) to `BrickBreaker` that synchronizes with Flame's `overlays`, turn off `debugMode`, and move spawning the ball, bat, and bricks into a `startGame()` method triggered by tapping the screen (`TapCallbacks`) or pressing Space or Enter. Transition to `gameOver` when the ball exits the bottom and `won` when the final brick breaks. Then create a Flutter wrapper `GameApp` (`lib/src/widgets/game_app.dart`, importing `package:material_ui/material_ui.dart`) using the `'Press Start 2P'` Google Font and a gradient background that displays `GameWidget` overlays for `'TAP TO PLAY'`, `'G A M E O V E R'`, and `'Y O U W O N ! ! !'`. Also add the required Android and macOS network permissions for `google_fonts`.
생성된 코드 이해
PlayState로 오버레이 관리
lib/src/brick_breaker.dart에서 playState setter는 게임 상태를 Flame의 overlays 관리자와 동기화합니다.
late PlayState _playState;
PlayState get playState => _playState;
set playState(PlayState playState) {
_playState = playState;
switch (playState) {
case PlayState.welcome:
case PlayState.gameOver:
case PlayState.won:
overlays.add(playState.name);
case PlayState.playing:
overlays.remove(PlayState.welcome.name);
overlays.remove(PlayState.gameOver.name);
overlays.remove(PlayState.won.name);
}
}
startGame()를 onLoad()에서 분할하면 플레이어가 화면을 탭하거나(onTapDown) 스페이스바 또는 Enter 키를 눌러 언제든지 게임을 시작하거나 다시 시작할 수 있습니다.
GameWidget의 매핑 오버레이
lib/src/widgets/game_app.dart에서 GameWidget.controlled는 BrickBreaker 인스턴스를 구성하고 각 PlayState 이름을 Flutter 위젯 오버레이에 매핑합니다.
child: GameWidget.controlled(
gameFactory: BrickBreaker.new,
overlayBuilderMap: {
PlayState.welcome.name: (context, game) => Center(
child: Text(
'TAP TO PLAY',
style: Theme.of(context).textTheme.headlineLarge,
),
),
// ...
},
),
overlayBuilderMap의 각 키는 overlays.add(...) 및 overlays.remove(...)에 전달된 오버레이 이름과 일치해야 합니다.
게임 실행 및 테스트
google_fonts의 플랫폼 네트워크 권한이 업데이트되었으므로 앱을 중지하고 다시 실행합니다. 실행 시 'TAP TO PLAY'가 표시되고, 탭하거나 스페이스바를 누르면 게임이 시작되며, 공을 놓치면 'G A M E O V E R'가 표시되는지 확인합니다.
10. 점수 기록
Antigravity에 스코어카드와 애니메이션 오버레이를 추가하라는 프롬프트 입력
이 마지막 단계에서는 ValueNotifier를 사용하여 Flame에서 Flutter로 플레이어의 점수를 노출하고 flutter_animate로 오버레이를 다듬습니다. Antigravity에서 다음 프롬프트를 전송합니다.
Track the player's score in `BrickBreaker` using a `ValueNotifier<int> score` that resets in `startGame()` and increments whenever a brick is broken. Using `package:material_ui/material_ui.dart`, create a `ScoreCard` widget (`lib/src/widgets/score_card.dart`) above the `GameWidget` that listens to `score`, and an `OverlayScreen` widget (`lib/src/widgets/overlay_screen.dart`) using `flutter_animate` to slide in the overlay title and pulse the subtitle in and out.
생성된 코드 이해
ValueNotifier를 사용하여 Flame 상태를 Flutter에 연결
lib/src/brick_breaker.dart에서 BrickBreaker는 final ValueNotifier를 노출합니다. 이는 startGame()에서 재설정되고 Brick가 적중될 때마다 증가합니다.
lib/src/widgets/score_card.dart에서 ScoreCard는 ValueListenableBuilder를 사용하므로 score.value가 변경될 때 점수 텍스트만 다시 빌드됩니다.
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<int>(
valueListenable: score,
builder: (context, score, child) {
return Padding(
padding: const EdgeInsets.fromLTRB(12, 6, 12, 18),
child: Text(
'Score: $score'.toUpperCase(),
style: Theme.of(context).textTheme.titleLarge!,
),
);
},
);
}
flutter_animate으로 오버레이에 애니메이션 적용
lib/src/widgets/overlay_screen.dart에서 OverlayScreen는 표준 Text 위젯에 flutter_animate 효과를 연결하여 제목을 슬라이드하고 부제목을 펄스합니다.
Text(
title,
style: Theme.of(context).textTheme.headlineLarge,
).animate().slideY(duration: 750.ms, begin: -3, end: 0),
const SizedBox(height: 16),
Text(subtitle, style: Theme.of(context).textTheme.headlineSmall)
.animate(onPlay: (controller) => controller.repeat())
.fadeIn(duration: 1.seconds)
.then()
.fadeOut(duration: 1.seconds),
flutter_animate 및 Flutter 애니메이션의 강력한 기능을 자세히 알아보려면 flutter_animate 패키지 문서와 Flutter의 애니메이션 Codelab을 참고하세요.
게임 실행 및 테스트
게임을 핫 리스타트합니다. 모든 준비가 완료되었으므로 이제 6가지 Flutter 타겟 플랫폼에서 벽돌 깨기 게임을 플레이할 수 있습니다.
|
|
11. 마무리
수고하셨습니다 Flutter, Flame, Google Antigravity를 사용하여 완전한 2D 아케이드 게임을 빌드했습니다.
빌드한 항목
- 모바일, 데스크톱, 웹에서 깔끔하게 확장되고 레터박스 처리되는 고정 해상도 2D Flame 게임 세계(
BrickBreaker및PlayArea) HasCollisionDetection, 히트박스, 프레임 속도 독립 속도 업데이트를 사용하는 물리 및 충돌 구성요소(Ball,Bat,Brick)- 터치 및 마우스 드래그(
DragCallbacks)를 키보드 기반MoveToEffect애니메이션 및 지연된RemoveEffect정리와 결합하는 멀티모달 재생 컨트롤 및 불꽃 효과 GameWidget.controlled오버레이, 실시간 점수 업데이트를 위한ValueNotifier상태 관리,google_fonts,flutter_animate를 사용한 Flutter UI 통합
다음 단계
Antigravity에 계속 프롬프트를 입력하여 나만의 게임을 만들어 보세요. 다음은 시도해 볼 수 있는 몇 가지 방법입니다.
- 복고풍 아케이드 음향 효과: Antigravity에 패들 타격, 벽 튕김, 벽돌 파괴에 대한
flame_audio(또는 합성 오디오 효과)를 추가하라는 프롬프트를 입력합니다. - 파워업 및 멀티볼: 깨진 벽돌에서 떨어지는 파워업 캡슐을 생성하여 배트를 넓히거나, 공의 속도를 늦추거나, 공을 세 개로 나눕니다.
- 여러 레벨 및 최고 점수:
shared_preferences를 사용하여 플레이어의 최고 점수를 저장하고 후속 레벨을 위한 새로운 벽돌 레이아웃을 설계합니다.
다음 단계
다음 관련 Codelab을 확인하세요.

