Search code examples
flutterflame

How to make an animated sprite look like it's walking forward in Flame Game?


I've got a moving sprite that animates over a loop of 4 images to make it look like it's walking in one spot. I want to make the sprite move forward by a certain amount when I click a button. I've tried looking for how this might be done, but it's just made me confused. I've found this information sheet by Flame Game that explain effects, but I don't understand how to apply it to what I've got (https://docs.flame-engine.org/1.0.0/effects.html).

This is the constructor for the class that makes the dog move:

  Dog()
      : super(
    priority: 1,
    playing: true,
    scale: Vector2(1, 1),
    size: Vector2.all(50),
  ) {
    animation = SpriteAnimation.spriteList(runPictures, stepTime: 0.2);
    position = Vector2(150.0, 150.0);
  }

I want the dog to move 100 pixels towards the top of the screen, while it's going through the loop above, when a button is clicked. This button would send it to a class that would make it move. If someone could provide sample code or a useful tutorial, it would be very helpful.


Solution

  • You are on the right track, you want to add a MoveByEffect to the component.

    I assume that you already have the button set up and that you have access to an instance of the Dog component from there, then you simply add the effect to the component:

    final dog = Dog(...);
    
    // Or whatever callback you have for the button
    void onTap() {
      dog.add(
        MoveByEffect(Vector2(0, -100), EffectController(duration: 1)),
      );  
    }
    

    This will move the dog 100px upwards during one second.