You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:03:22