Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Building Games with Flutter

You're reading from  Building Games with Flutter

Product type Book
Published in Jun 2022
Publisher Packt
ISBN-13 9781801816984
Pages 224 pages
Edition 1st Edition
Languages
Concepts
Author (1):
Paul Teale Paul Teale
Profile icon Paul Teale

Table of Contents (17) Chapters

Preface 1. Part 1: Game Basics
2. Chapter 1: Getting Started with Flutter Games 3. Chapter 2: Working with the Flame Engine 4. Chapter 3: Building a Game Design 5. Part 2: Graphics and Sound
6. Chapter 4: Drawing and Animating Graphics 7. Chapter 5: Moving the Graphics with Input 8. Chapter 6: Playing Sound Effects and Music 9. Chapter 7: Designing Your Own Levels 10. Chapter 8: Scaling the Game for Web and Desktop 11. Part 3: Advanced Games Programming
12. Chapter 9: Implementing Advanced Graphics Effects 13. Chapter 10: Making Intelligent Enemies with AI 14. Chapter 11: Finishing the Game 15. Other Books You May Enjoy Appendix: Answers

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.

You have been reading a chapter from
Building Games with Flutter
Published in: Jun 2022 Publisher: Packt ISBN-13: 9781801816984
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}