Flame新版本中如何替换旧版followComponent方法实现相机跟随?
Flame适配最新版本报错修复
问题描述
我是Flame初学者,使用教程中的代码时遇到报错。
教程原代码:
import 'dart:ui'; import 'package:flame/game.dart'; import 'components/player.dart'; import '../helpers/direction.dart'; import 'components/world.dart'; class RayWorldGame extends FlameGame { final Player _player = Player(); final World _world = World(); @override Future<void> onLoad() async { await add(_world); add(_player); _player.position = _world.size / 2; camera.followComponent(_player, worldBounds: Rect.fromLTRB(0, 0, _world.size.x, _world.size.y)); } void onJoypadDirectionChanged(Direction direction) { _player.direction = direction; } }
报错信息:
Error: The method 'followComponent' isn't defined for the class 'CameraComponent'.
修复方案
新版Flame中CameraComponent的API有更新,followComponent方法已被移除,需改用camera.viewfinder.follow,同时世界边界类型需替换为Rectangle。
修改后的代码:
import 'dart:ui'; import 'package:flame/game.dart'; import 'package:flame/geometry.dart'; // 新增导入Rectangle所需包 import 'components/player.dart'; import '../helpers/direction.dart'; import 'components/world.dart'; class RayWorldGame extends FlameGame { final Player _player = Player(); final World _world = World(); @override Future<void> onLoad() async { await add(_world); add(_player); _player.position = _world.size / 2; // 替换相机跟随方法,更新世界边界类型 camera.viewfinder.follow(_player, worldBounds: Rectangle(0, 0, _world.size.x, _world.size.y)); } void onJoypadDirectionChanged(Direction direction) { _player.direction = direction; } }
核心修改点:
- 新增
package:flame/geometry.dart导入,用于使用Rectangle类 - 将
camera.followComponent替换为camera.viewfinder.follow - 用
Rectangle构造函数替代Rect.fromLTRB来定义世界边界
内容的提问来源于stack exchange,提问作者senchabrest
相关产品推荐
相关产品推荐

