flutterdartflame

Flutter Flame character speed varies across devices


I am building a flame game similar to Jetpack Joyride. It has a character on the screen, and when the user taps and holds the screen, the character excelerates upwards, and if the user doesn't tap the screen anymore, the character moves downwards.

Here is my code of the Game class:

class MyGame extends FlameGame with TapCallbacks {
  // The character
  late Slime slime;

  double speed = 0;
  bool pressing = false;
  bool movementInitialized = false;

  @override
  FutureOr<void> onLoad() {
    addAll([
      slime = Slime(),
    ]);
  }

  @override
  void onTapDown(TapDownEvent event) {
    pressing = true;
    if (!movementInitialized) {
      movementInitialized = true;
    }
    super.onTapDown(event);
  }

  @override
  void onTapUp(TapUpEvent event) {
    pressing = false;
    super.onTapUp(event);
  }

  @override
  void update(double dt) {
    super.update(dt);
    if (movementInitialized) {
      if (pressing && speed > -GameConfig.maxSpeed) {
        speed -= GameConfig.tapGravity;
      } else if (!pressing && speed < GameConfig.maxSpeed) {
        speed += GameConfig.slimeGravity;
      }
      slime.position.y += speed;
    }
  }
}

It works fine, but on some devices the movement seems to be faster than on other devices. I also added some obstacles that move from right to left and they re faster on some devices than on others. So my only guess is that the frame rate is higher on some devices so the update method gets called more frequently. Is that correct? If yes, what better way is there to implement this?


Solution

  • You need to use dt variable (Delta Time) it's the elapsed time between current and past game loop. If the device is faster, there is more game loops in same amount of time resulting in faster character.

    maybe something like that do the job :

    slime.position.y += speed * dt;