0

我有一个使用该flame库的颤振应用程序。我试图让一个物体在颤动游戏中移动。当我运行该update函数时,我收到以下错误:

The method '*' was called on null.
Receiver: null
Tried calling: *(0.0)

似乎某些东西没有初始化,并且在初始化update某些东西之前运行了该函数。当我注释掉player.update(t)它时,它可以工作,但不会调用更新函数。我在做什么错广告我该如何解决?这是我的代码:

游戏控制器类

class GameController extends Game {
  Size screenSize;
  Player player;

  GameController() {
    initialize();
  }

  void initialize() async {
    final initDimetion = await Flame.util.initialDimensions();
    resize(initDimetion);
    player = Player(this);
  }

  void render(Canvas c) {
    Rect bgRect = Rect.fromLTWH(0, 0, screenSize.width, screenSize.height);
    Paint bgPaint = Paint()..color = Color(0xFFFAFAFA);
    c.drawRect(bgRect, bgPaint);

    player.render(c);
  }

  void update(double t) {
    if (player is Player) { // Tried adding this if statement but it didn't work
      player.update(t);
    }
  }

  void resize(Size size) {
    screenSize = size;
  }
}

玩家等级

class Player {
  final GameController gameController;
  Rect playerRect;
  double speed;

  Player(this.gameController) {
    final size = 40.0;

    playerRect = Rect.fromLTWH(gameController.screenSize.width / 2 - size / 2,
        gameController.screenSize.height / 2 - size / 2, size, size);
  }

  void render(Canvas c) {
    Paint color = Paint()..color = Color(0xFF0000FF);
    c.drawRect(playerRect, color);
  }

  void update(double t) {
    double stepDistance = speed * t;
    Offset stepToSide = Offset.fromDirection(90, stepDistance);
    playerRect = playerRect.shift(stepToSide);
  }
}
4

1 回答 1

1

您永远不会将 Player 的 speed 属性初始化为一个值。所以speed * t在 Player.update 中会导致这个错误。

只需在构造函数中初始化速度属性

  Player(this.gameController) {
    final size = 40.0;
    this.speed = 0;
    playerRect = Rect.fromLTWH(gameController.screenSize.width / 2 - size / 2,
        gameController.screenSize.height / 2 - size / 2, size, size);
  }
于 2020-04-18T00:56:54.190 回答