Update function in Flutter Flame

The elements that are in the game need to be constantly redrawn according to the current state of the game; to understand this more clearly, let's see an example:

Suppose that a game element represented by a sprite (an image), which in this example we will call as "player"; when the user clicks on a button, then the player must update its position; this update is applied in-game by a function called update().

As we saw in the example of the moving circle, it is this function that is responsible for updating the position of the circle on the screen.

The update() function is as its name indicates, an update function, which receives a parameter called "deltatime" (dt) that tells us

the time that has elapsed since the previous frame was drawn. You should use this variable to make your component move at the same speed on all devices.

When updating any aspect of the game through the update() function, it is automatically reflected through the render() function and with this, the game update at a graphical level.

In Flame, the update() method is used to update the game state on each interaction; as we explained before in the GameLoop post, it is essential to perform any on-screen update. This method is called automatically by the Flame game engine at a relatively constant time which as we mentioned before, how often this function is called depends on the processing speed of the device used.

The update function receives a parameter called DeltaTime which is the time passed since the last invocation of said function.

Within the update() method, you can perform tasks such as updating the position, scaling... and in essence, any operation you want to perform in the game; a common validation is to check for collisions, among other operations.

Here is a basic example of how the update() method can be implemented in a game class in Flame:

 

import 'package:flame/game.dart';

class MyGame extends FlameGame{
  @override
  void update(double dt) {
    super.update(dt);
  }
}

In this example, a class MyGame is defined that extends FlameGame. The update() method is overridden to perform the operations mentioned above; It is important to note that this function is also available in Flame components and not only at the level of Game-type classes.

It is important to call the super.update(dt) method at the end of the update() method, as this takes care of updating the game components and rendering them to the screen.

I hope this information is useful for you to understand the function of the update() method in Flame.

The Game loop is used by all implementations of Game classes and their components:

https://docs.flame-engine.org/1.6.0/flame/game.html

- 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.