1. 簡介
建構項目
Flame 是以 Flutter 為基礎的 2D 遊戲引擎,在本程式碼實驗室中,您將打造一款遊戲,靈感來自 70 年代的經典電玩遊戲:Steve Wozniak 的《Breakout》。您將使用 Google Antigravity,逐步提示代理為球拍、球和磚塊建構 Flame Component,使用 Flame Effect 建立球拍移動動畫,並將 Flame 與 Flutter 的狀態管理系統整合。
完成後,遊戲應如下方 GIF 動畫所示,但速度會稍慢:

完成的遊戲符合下列規定:
- 可在 Flutter 支援的所有六個平台上運作:Android、iOS、Linux、macOS、Windows 和網頁。
- 使用 Flame 的遊戲迴圈,維持至少 60 fps。
- 使用
google_fonts和flutter_animate等 Flutter 套件,重現 70 和 80 年代街機遊戲的氛圍。
學習旅程
這個程式碼實驗室會逐步引導您建構遊戲:
- 設定 Flutter 環境:為目標平台設定 Flutter 和 Google Antigravity。
- 建立專案:提示 Antigravity 使用 Flame、
flutter_animate、google_fonts和material_ui建立空白 Flutter 專案。 - 建立遊戲:設定固定解析度攝影機,並在遊戲世界中加入
PlayArea元件。 - 顯示球:新增由 Flame 遊戲迴圈和速度向量驅動的移動
Ball元件。 - 四處彈跳:啟用碰撞偵測和碰撞箱,讓球從牆壁彈開。
- 擊球:新增玩家控制的
Bat,支援拖曳和鍵盤輸入,並使用MoveToEffect。 - 打破牆壁:生成
Brick元件網格,並在磚塊破裂時調整球速。 - 贏得遊戲:使用
GameWidget.controlled管理遊戲狀態,並顯示復古的 Flutter 小工具疊加層。 - 計分:使用
ValueNotifier將玩家分數與 Flutter UI 同步,並使用flutter_animate建立疊加層動畫。
課程內容
- 如何與 Google Antigravity 協作,反覆建構及自訂 Flame 遊戲。
- Flame 的基本運作方式,從
GameWidget開始。 - 如何使用遊戲迴圈,讓移動不受影格率影響。
- Flame 的
Component運作方式 (類似 Flutter 的Widget)。 - 如何使用碰撞箱偵測及回應碰撞。
- 如何使用
Effect建立動畫並移除Component。 - 如何在 Flame 遊戲上疊加 Flutter
Widget。 - 如何將 Flame 與 Flutter 的狀態管理功能整合。
必要條件
- 對 Flutter 和 Dart 語法有基本瞭解。
2. 設定 Flutter 環境
編輯者
本程式碼實驗室會使用 Google Antigravity 做為 AI 優先開發環境。在每個步驟中,您會提示 Antigravity 生成或改良遊戲元件、查看生成程式碼中的重要 Flame 概念,並視需要探索不同時代風格的街機遊戲。
選擇開發目標
Flutter 可為多個平台製作應用程式。應用程式可在下列任一作業系統上執行:
- iOS
- Android
- Windows
- macOS
- Linux
- 網路
選擇一個作業系統做為開發目標是常見的做法。這個作業系統就是開發目標:開發過程中用來執行應用程式的 OS。

舉例來說,假設您使用 Windows 筆電開發 Flutter 應用程式,並選擇 Android 做為開發目標,則您會使用 USB 傳輸線將 Android 裝置連接至 Windows 筆電,而開發中的應用程式會在連接的 Android 裝置 (或 Android Emulator) 上執行。您也可以選擇 Windows 做為開發目標,這樣一來,開發中的應用程式就會在編輯器旁,以 Windows 傳統型應用程式的形式執行。
請先選擇,再繼續操作。您日後隨時可以在其他作業系統上執行應用程式。選擇開發目標可讓後續步驟更順利。
安裝 Flutter
如需安裝 Flutter SDK 的最新操作說明,請前往 docs.flutter.dev。
Flutter 網站上的操作說明涵蓋安裝 SDK、平台專屬工具和編輯器外掛程式。請安裝下列軟體,以便進行本程式碼實驗室:
- Flutter SDK
- Google Antigravity,並啟用官方 Dart 和 Flutter 外掛程式 (可在外掛程式市集的「Build with Google」部分找到)。
- 所選開發目標的編譯器軟體 (例如,Visual Studio 適用於 Windows,Xcode 適用於 macOS 或 iOS)。
在下一個步驟中,您將提示 Antigravity 建立 Flutter 專案,並建構初始 Flame 遊戲。
疑難排解
如果遇到設定問題,下列 Stack Overflow 問答或許能提供協助:
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));
}
執行及測試遊戲
在所選開發目標上執行應用程式,確認一切正常運作。系統會顯示一個新視窗,背景為空白黑色。世界上最簡單的電玩遊戲,現在以 60 FPS 呈現!

4. 建立遊戲
評估遊戲
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和火焰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))。 - 將
PlayArea新增至world,透過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
將 HasCollisionDetection 混入新增至 BrickBreaker,可追蹤元件命中框 (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,在 100 毫秒內流暢地為球棒加上動畫:
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 新增磚塊
在 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 列舉,將 Flame 遊戲嵌入具有疊加層的樣式 Flutter GameApp 小工具,並設定 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 會將 flutter_animate 效果鏈結至標準 Text 小工具,讓標題滑入並讓副標題脈動:
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 動畫程式碼實驗室。
執行及測試遊戲
熱重新啟動遊戲。一切就緒後,您現在可以在六個 Flutter 目標平台中的任何一個上玩打磚塊遊戲:
|
|
11. 恭喜
恭喜!您已使用 Flutter、Flame 和 Google Antigravity 打造出完整的 2D 街機遊戲。
建構內容
- 固定解析度的 2D Flame 遊戲世界 (
BrickBreaker和PlayArea),可在行動裝置、電腦和網頁上縮放及加上黑邊。 - 物理和碰撞元件 (
Ball、Bat和Brick),使用HasCollisionDetection、命中框和與影格率無關的速度更新。 - 多模式播放器控制項和 Flame 效果:結合觸控和滑鼠拖曳 (
DragCallbacks)、鍵盤驅動的MoveToEffect動畫,以及延遲的RemoveEffect清理。 - 使用
GameWidget.controlled疊加層、ValueNotifier狀態管理 (用於即時更新分數)、google_fonts和flutter_animate整合 Flutter UI。
下一步該做什麼?
繼續提示 Antigravity,打造專屬遊戲!不妨試試以下幾種做法:
- 懷舊街機音效:提示 Antigravity 為球拍擊球、牆壁反彈和磚塊破壞等動作,加入
flame_audio(或合成音效)。 - 強化道具和多球模式:擊碎磚塊後,會掉落強化道具膠囊,可讓球拍變寬、球速變慢,或將球分裂成三顆。
- 多個關卡和最高分:使用
shared_preferences儲存玩家的最高分,並為後續關卡設計新的磚塊版面配置。
後續步驟
查看一些相關的程式碼實驗室:

