Update function in Flutter Flame, Update position of a Sprite

As mentioned in previous entries, for any update that we want to be done in the game, it must be done through the update() method; with this, we can update different aspects of some component of our game such as size, position, etc. During the update, we are going to change the position of the sprite by setting the value of x and y on the position property; in this example, we see a minimal implementation of how to update the position of a sprite:

import 'package:flame/game.dart';
import 'package:flame/components/sprite.dart';
class MyGame extends Game {
 late SpriteComponent sprite;
 @override
 Future<void> onLoad() async {
   sprite = SpriteComponent.fromImage(
     await images.load('sprite.png'),
     x: 20,
     y: 100,
   );
 }
 @override
 void update(double dt) {
   // actualizar la posición del sprite aquí
   sprite.x += 10 * dt;
 }
 @override
 void render(Canvas canvas) {
   sprite.render(canvas);
 }
}

In this example, the sprite will start at position (20, 100) and move horizontally to the right on each iteration of the update() function.

The position is updated in the update method by calculating sprite.x += 10 * dt, which adds 10 pixels per second; remember that the parameter of dt is the time since the previous call; therefore, when a second passes, it will move 10 pixels; this is very important since the movement will be constant regardless of the speed of the game and it is precisely by multiplying the position by the factor of dt, which is the time elapsed since the last frame in seconds.

Here is an example of how to update the position of a sprite in Flame's Game class:

To move a PositionComponent or a Sprite in general, we have the position property, which receives a Vector2; we can use the update() function to update the position of the image and scroll it automatically:

class PlayerImageSpriteComponent  extends SpriteComponent{
  ***
  @override
  void update(double dt) {
    position = Vector2(centerX++, centerY++);
    super.update(dt);
  }
}

In this other example, the dt factor is not used and therefore the update will be quite fast and different for each device; so that the speed is constant regardless of the processing speed, we have:

class PlayerImageSpriteComponent  extends SpriteComponent{
  ***
  @override
  void update(double dt) {
    position = Vector2(centerX++, centerY++) * dt;
    super.update(dt);
  }
}

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.