Book Image

Building Games with Flutter

By : Paul Teale
Book Image

Building Games with Flutter

By: Paul Teale

Overview of this book

With its powerful tools and quick implementation capabilities, Flutter provides a new way to build scalable cross-platform apps. In this book, you'll learn how to build on your knowledge and use Flutter as the foundation for creating games. This game development book takes a hands-on approach to building a complete game from scratch. You'll see how to get started with the Flame library and build a simple animated example to test Flame. You'll then discover how to organize and load images and audio in your Flutter game. As you advance, you'll gain insights into the game loop and set it up for fast and efficient processing. The book also guides you in using Tiled to create maps, add sprites to the maps that the player can interact with, and see how to use tilemap collision to create paths for a player to walk on. Finally, you'll learn how to make enemies more intelligent with artificial intelligence (AI). By the end of the book, you'll have gained the confidence to build fun multiplatform games with Flutter.
Table of Contents (17 chapters)
1
Part 1: Game Basics
5
Part 2: Graphics and Sound
11
Part 3: Advanced Games Programming

Creating a simple example animation

Here is a code sample for you to run to show how easy it is to draw and animate a simple shape.

To run this example, follow these steps:

  1. First, create a new project in the command line by running the following command:
    flutter create goldrush
  2. Open the goldrush folder that Flutter created in your code editor, and then open the pubspec.yaml file.
  3. Update the description to the following:
    description: Flutter game from Building Games with Flutter
  4. Update the environment SDK to the following:
      sdk: ">=2.17.0 <3.0.0"

This is the latest version of the SDK at the time of writing the book, and supports the latest features of Flutter and Dart.

  1. Under the dependencies section, we need to add a library called Flame (which we will talk more about in the next chapter):
    cupertino_icons: ^1.0.2
    flame: 1.0.0

Flame is a great library and provides us with a lot of functionality needed to build games using Flutter and Dart.

  1. Now that we have finished updating the pubspec.yaml file, save the changes.
  2. After saving the changes, your code editor should download the new dependency. If this doesn't update, you can manually run the following command from the command line in the same directory as your project:
    flutter pub get
  3. Next, open the lib/main.dart file and delete all the boilerplate code.
  4. Then, we need to set up the imports we will need for this example:
    import 'dart:ui';
    import 'package:flame/flame.dart';
    import 'package:flame/palette.dart';
    import 'package:flutter/material.dart';
    import 'package:flame/game.dart';
  5. Under this, we need to add our main function to initialize the game and the screen:
    void main() async {
      final goldRush = GoldRush();
      WidgetsFlutterBinding.ensureInitialized();
      await Flame.device.fullScreen();
      await Flame.device.setPortrait();
      runApp(
        GameWidget(game: goldRush)
      );
    }

Here, we set up our GoldRush game object (which we will define next) and told Flame that we want to run the game in full screen and in portrait mode. We also ran the app, passing the GameWidget.

  1. Next, let's set up the game widget and some variables that we will use in the game:
    class GoldRush with Loadable, Game {
      static const int squareSpeed = 250;
      static final squarePaint = 
        BasicPalette.green.paint();
      static final squareWidth = 100.0, squareHeight = 
        100.0;
      late Rect squarePos;
      int squareDirection = 1;
      late double screenWidth, screenHeight, centerX, 
        centerY;

Let's break down what we did here:

  • Here, we set up the animation speed of the square to be 250; you can adjust this to a higher number to make the animation faster or lower to make the animation slower.
  • We set the color of our box to green.
  • The width and height of the box are set to a fixed size of 100 pixels.
  • Because we will adjust the position of the box, we use Rect for the square position, which will be initialized in onLoad once we have calculated the center of the screen for the starting position.
  • We set the direction to be a positive value, which will increase the x value and move the box to the right.
  • Finally, we set up the variables for the screen width and height, and the center of the screen.
  1. In the onLoad function, we will calculate the center starting position of the box based on the screen size:
      @override
      Future<void> onLoad() async {
        super.onLoad();
        screenWidth =
          MediaQueryData.fromWindow(window).size.width;
        screenHeight =
          MediaQueryData.fromWindow(window).size.height;
        centerX = (screenWidth / 2) - (squareWidth / 2);
        centerY = (screenHeight / 2) - (squareHeight / 2);
        squarePos = Rect.fromLTWH(centerX, centerY, 
          squareWidth, squareHeight);
      }
  2. Next, we will define the render function, which draws the square on the screen at its current position:
      @override
      void render(Canvas canvas) {
        canvas.drawRect(squarePos, squarePaint); 
      }
  3. Next, we update the square position every frame based on its speed and direction, plus the time that has elapsed since the previous frame.

Then, if the position of the square has reached the edge of the screen, we can flip the direction of the square:

  @override
  void update(double deltaTime) {
    squarePos = squarePos.translate(squareSpeed *
      squareDirection * deltaTime, 0);
    if (squareDirection == 1 && squarePos.right >
    screenWidth) {
      squareDirection = -1;
    } else if (squareDirection == -1 && squarePos.left
      < 0) {
      squareDirection = 1;
    }
  }
}
  1. Now, we can run the example and see our simple green square animating from left to right, reversing its direction when it hits the side of the screen.

Now, we have gone through a simple animation example to show how easy it is to get started and to give you a feel for game programming with Flutter.

Feel free to play with the code, maybe changing the color of the square or adding more squares at a different position. In the next chapter, we will dig deeper into this code.