1. 简介
构建内容
Flame 是一个基于 Flutter 的 2D 游戏引擎。在此 Codelab 中,您将构建一款游戏,其灵感源自 70 年代的一款经典电子游戏,即 Steve Wozniak 的打砖块。您将使用 Google Antigravity,逐步提示智能体为球拍、球和砖块构建 Flame Component,使用 Flame Effect 为球拍的移动添加动画效果,并将 Flame 与 Flutter 的状态管理系统集成。
完成后,您的游戏应如下面的 GIF 动画所示,不过速度会稍慢一些:

您完成的游戏符合以下要求:
- 可在 Flutter 支持的所有六个平台上运行:Android、iOS、Linux、macOS、Windows 和 Web。
- 使用 Flame 的游戏循环,保持至少 60 fps 的帧率。
- 使用
google_fonts和flutter_animate等 Flutter 软件包,重现 70 年代和 80 年代街机游戏的体验。
您的学习之旅
此 Codelab 将引导您逐步构建游戏:
- 设置 Flutter 环境 - 为目标平台配置 Flutter 和 Google Antigravity。
- 创建项目 - 提示 Antigravity 使用 Flame、
flutter_animate、google_fonts和material_ui构建一个空的 Flutter 项目。 - 创建游戏 - 配置固定分辨率相机,并向游戏世界添加
PlayArea组件。 - 显示球 - 添加由 Flame 的游戏循环和速度矢量驱动的移动
Ball组件。 - 弹跳 - 启用碰撞检测和碰撞箱,让球从墙壁上弹开。
- 击球 - 添加一个由玩家控制的
Bat,支持拖动和键盘输入,并使用MoveToEffect。 - 打破墙壁 - 生成一个由
Brick组件组成的网格,并随着砖块破碎而提高球的速度。 - 赢得游戏 - 管理游戏状态,并使用
GameWidget.controlled显示复古风格的 Flutter widget 叠加层。 - 记录得分 - 使用
ValueNotifier将玩家的得分与 Flutter 界面同步,并使用flutter_animate为叠加层添加动画效果。
学习内容
- 如何与 Google Antigravity 协作,以迭代方式构建和自定义 Flame 游戏。
- Flame 的基本工作原理,从
GameWidget开始。 - 如何使用游戏循环实现与帧速率无关的移动。
- 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
- 网络
一种常见的做法是选择一个操作系统作为目标开发平台。这是您的应用在开发期间运行的操作系统。

例如,假设您开发 Flutter 应用使用的是 Windows 笔记本电脑。如果选择 Android 作为目标开发平台,您需要使用 USB 线将 Android 设备连接到 Windows 笔记本电脑,并且您在开发的应用将在该连接的 Android 设备(或 Android 模拟器)上运行。或者,您也可以选择 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 问题和解答可能会有所帮助:
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 游戏引擎中很常见。
在最初创建《打砖块》游戏时,惯例是将原点放在左上角。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 应用由 widget 树组成,而 Flame 游戏则维护组件树。
Flutter 的 widget 树是一个不可变描述,用于更新持久且可变的 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),并在每个游戏 tick 触发碰撞回调。
在 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 中,移除组件是一条排队命令,只有在当前回调完成后,在下一个游戏 tick 之前,砖块才会从组件树中移除。
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 widget 添加欢迎、游戏结束和获胜叠加层!
9. 赢得游戏
提示 Antigravity 添加 PlayState 和 Flutter 叠加层
在此步骤中,您将引入一个 PlayState 枚举,将 Flame 游戏嵌入到带有叠加层的样式化 Flutter GameApp widget 中,并为 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 widget 叠加层:
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 widget 上,以滑入标题并使副标题产生脉冲效果:
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。
运行和测试游戏
热重启游戏。一切就绪后,您现在可以在六个 Flutter 目标平台中的任何一个上玩打砖块游戏:
|
|
11. 恭喜
恭喜!您已使用 Flutter、Flame 和 Google Antigravity 构建了一款完整的 2D 街机游戏。
您构建的内容
- 一个固定分辨率的 2D Flame 游戏世界(
BrickBreaker和PlayArea),可在移动设备、桌面设备和 Web 上清晰地缩放和显示黑边。 - 物理和碰撞组件(
Ball、Bat和Brick),使用HasCollisionDetection、碰撞箱和与帧速率无关的速度更新。 - 多模态玩家控制和 Flame 效果:结合了轻触和鼠标拖动 (
DragCallbacks) 与键盘驱动的MoveToEffect动画和延迟的RemoveEffect清理。 - Flutter 界面集成:使用
GameWidget.controlled叠加层、ValueNotifier状态管理(用于实时更新得分)、google_fonts和flutter_animate。
后续步骤
继续向 Antigravity 发出提示,打造属于您自己的游戏!不妨尝试以下几种方法:
- 复古街机音效:提示 Antigravity 为球拍击球、墙壁反弹和砖块破坏添加
flame_audio(或合成音效)。 - 强化道具和多球模式:击碎砖块后,会掉落强化道具胶囊,这些道具可以加宽球拍、减慢球速或将球一分为三。
- 多个关卡和最高得分:使用
shared_preferences保留玩家的最高得分,并为后续关卡设计新的砖块布局。
接下来怎么做?
查看以下相关 Codelab:

