Search code examples
flutterflame

Component always move a little more than I expected


Hallo here is my code for a SpriteComponent, which starts outside of screen and should move into the screen after I trigger it.

@override
  void update(double dt) {
    if (gameRef.shouldMoveCharacter) {
      if (position.x < 0) {
        position += velocity * dt;
        acceleration++;
        velocity.x = velocity.x + acceleration;
      }
    super.update(dt);
  }
}

But this component will always move a little more right, which makes a small gaps between them as the screenshotenter image description here I assumed that the last velocity.x is too big that let Component run too much, But considered of different size of phone, how to solve this problem? Also I try to achieve a easyOut effect, but have no idea how to do that, since I am using the old version, so there is no MoveEffect T T. Thanks for the help!


Solution

  • Since velocity * dt can bring position to be larger than 0 you'll have to clamp the position. I'm guessing that your anchor is topLeft, then you can just add this to the end of your if:

    import dart:math;
    
    ...
    
    position.x = min(position.x, 0);