我有一个使用flame
库的flutter应用程序。我正在尝试使对象在 flutter 打游戏中移动。当我运行update
函数时,出现以下错误:
The method '*' was called on null.
Receiver: null
Tried calling: *(0.0)
似乎未初始化某些东西,并且在初始化某些东西之前运行了
update
函数。当我注释掉player.update(t)
时,它可以工作,但不会调用update函数。我在做错广告时该怎么解决?这是我的代码:游戏 Controller 类
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);
}
}
最佳答案
您永远不会将Player的speed属性初始化为一个值。因此Player.update中的speed * t
会导致此错误。
只需在构造函数中初始化speed属性
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);
}
关于flutter - Flutter更新给我这个错误:在空调用方法 '*',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61282624/