28,79 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 218
Veröffentlichungsjahr: 2022
The ultimate guide to creating multiplatform games using the Flame engine in Flutter 3
Paul Teale
BIRMINGHAM—MUMBAI
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Aaron Tanna
Senior Editor: Hayden Edwards
Content Development Editor: Rashi Dubey
Technical Editor: Saurabh Kadave
Copy Editor: Safis Editing
Project Coordinator: Rashika Ba
Proofreader: Safis Editing
Indexer: Manju Arasan
Production Designer: Aparna Bhagat
Marketing Coordinator: Anamika Singh
First published: June 2022
Production reference: 1310522
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80181-698-4
www.packt.com
To my beautiful wife, Mariel, and our adorable baby boy, Alfie, who I love with all my heart. In memory of my parents, Alfred and Vera Teale.
– Paul Teale
Paul Teale was born and raised in Leeds, West Yorkshire, before moving to London to pursue a career in software engineering. He has been a software engineer for 25+ years, covering backend, web, and mobile, where he has spent the last 13 years as a mobile developer covering Android and, more recently, Flutter. He has worked on many large projects during his career for companies including Discovery, Sky, Shazam, Visa, NBC, and Channel 5. He is a massive sci-fi fan and loves watching all the latest movies. He has been happily married to Mariel for the last 16 years and they live together in West London with their son, Alfie, and their 2 cats.
I would like to thank the people who are close to me and have supported me, especially my sisters, Sandra, Angela, and Debra.
And to my great friends, Philip Hartley, Iain Baker, and Linda Chan, who have helped me through so much in my life.
Linda Chan is a software engineer with a passion for exploring new technologies, teaching children to code, and developing fun games.
Working in London for start-ups and large companies, Linda began her career as a web developer and quickly transitioned to building native iOS apps. She saw huge potential in the early days of Flutter and has not looked back.
She now resides in Wales with her husband, daughter, and cat named Qwerty. Outside of coding, Linda enjoys drawing, playing the venova, guitar, piano and searching for Koroks in the land of Hyrule.
Samarth Agarwal is an experienced software engineer who specializes in the creation of mobile and web applications. He has been an active Flutter developer and has contributed numerous text and video-based courses on app development across a wide range of technologies. As a result of his content being used on multiple platforms, Samarth has helped over 20,000 students worldwide.
Currently, Samarth is a senior software engineer at QuillBot. When he is not working, he enjoys listening to music and playing first-person shooter games, not to mention that he enjoys exploring new locations and capturing everything through a lens.
Satyam Sharma is a Flutter developer from India. He has designed, developed, and shipped several apps on the Play Store.
He enjoys playing RPGs, reading books, and traveling in his free time. If he isn't busy with that, you can almost always find him looking for new project ideas. He goes by the username satyamx64 on the internet.
In this section, you will be introduced to Flutter and the Flame game engine and to the game we will build throughout the book by describing the design of the game.
This section contains the following chapters:
Chapter 1, Getting Started with Flutter GamesChapter 2, Working with the Flame EngineChapter 3, Building a Game DesignWelcome to Building Games with Flutter!
We will show you how to use Google's Flutter framework to build scalable games that work across mobile and web platforms. Flutter may seem a strange choice at first for building games because there are more established frameworks for making games, such as Unity or Unreal Engine, but a lot of these tools are very complex to learn and it takes a long time to start producing games with them.
Building on your existing knowledge of Flutter and Dart, we will take you through the steps needed to build a 2D game that will work across all supported platforms. Starting with the basics, we will build on this knowledge and gradually get on to more advanced game topics. By the end of the book, you will be able to make your own 2D games containing the following:
Animating graphics around the screenPlaying sound effects and musicControlling your player with keys, joystick, or gesturesDetecting when graphics collideCreating game level maps and navigating around themDesigning gamesScaling the game across different platformsAdvanced graphical effectsIntelligent enemiesWe will cover the core concepts with examples and then build on this, chapter by chapter, gradually building up a full game that works across different devices. Each chapter will contain code samples to help learn the building blocks of game development, along with the code, image, and sound resources to build our complete game. The game involves the player navigating around a map and avoiding the enemies while collecting as much gold as they can.
In this chapter, we want to delve a bit deeper into Flutter and Dart and what features they have that make them a great choice for game development. This will give you an understanding of why Flutter and Dart can be used for fast, smooth games across many platforms.
In this chapter, we will cover the following topics:
Working with FlutterUsing DartSummarizing the bookCreating a simple example animationWe have a lot to cover, so let's get started!
In this chapter, you should have your code editor set up along with the latest versions of Flutter and Dart installed. The book is based on Flutter v3.0.0, Dart 2.17.0, and Flame v1.0.0.
All the source code for this book can be downloaded from the Git repository at https://github.com/PacktPublishing/Building-Games-with-Flutter.git.
The source code for this chapter specifically can be found here: https://github.com/PacktPublishing/Building-Games-with-Flutter/tree/main/chapter01.
You will have used Flutter to build apps or websites before and may be wondering whether Flutter is good enough to make great games. Flutter is a great choice for game programming for the following reasons:
Flutter has very fast rendering times and is scalable across many platforms.Flutter games aim to draw at 60 frames per second (FPS) for smooth animation, or 120 FPS on devices capable of supporting higher refresh rates.Flutter code uses a single code base to make maintenance easier and enables the code to run on many devices.The Flutter core is written in C++, which makes games run at native speeds.Flutter is cost-effective due to being open source (businesses like Flutter because they don't have to pay for expensive licenses as they have to with some other frameworks).Unlike other frameworks, Flutter does not use native components and instead draws its own, all drawn with the lightning-fast Skia Graphics Engine. Skia is an open source graphics library that works on a variety of hardware and software platforms, which abstracts away platform-specific graphics APIs that are different on each platform. The APIs provide functionality for drawing shapes, text, and images.
Now that we have explained Flutter, let's delve deeper into the language that Flutter uses, Dart.
In this section, we will discuss Dart and the language features that make it a great fit for game development. We will discuss how Dart is compiled, and how it uses threads and garbage collection. We will also discuss great features such as how hot reload aids us in developing code fast.
Computer programming languages can be either static or dynamic. A static language will be compiled into machine code before it runs, such as C++. A dynamic language is executed by an interpreter, so it does not need to be compiled before running (such as JavaScript).
As programming languages evolved, virtual machines were invented, which made it easier to port a language to a new hardware platform. The code is converted to bytecode, which is then run on the virtual machine. Java is an example of a language that uses bytecode.
The virtual machine imitates hardware in software and can be ported to run on different hardware platforms, making the code portable.
As compiler technology evolved, just-in-time (JIT) compilers were invented, which improved the performance of code running on virtual machines by compiling the code on the fly.
Compiling a program into machine code before running became known as ahead-of-time (AOT) compilation. Dart is unique in that it supports both JIT and AOT compilation types, which provides a massive advantage for developers. Developers can distribute the app compiled with AOT for maximum speed and performance, which helps games run smoothly.
When running in JIT compilation mode, Flutter and Dart have an amazing feature called stateful hot reload that cuts down development time.
Flutter uses the JIT compiler to allow you to reload and run code in less than a second. This allows you to change code and see the changes reflected on the emulator or web browser instantly, while retaining the internal state of the game.
This is great for game development as you can modify code and see the effect of the change, which speeds up development massively. It feels like painting with code!
For instance, you might reposition a graphic by a few pixels or change a color. In traditional development, you would have to rebuild the code (which could take many minutes) to see the change, but in Flutter, this is instant.
Dynamic languages such as JavaScript communicate with the native code on the platform over a bridge, which is very slow. They do this for things such as drawing the native components of the platform they are running on.
The native bridge is used to provide an interface between dynamic code and native code for all code, sending state information for user interface (UI) components.
In Flutter, instead of this, Skia draws all the components on a canvas (and makes them look and feel like native components), so it bypasses the need for a native bridge.
This is massive because with a native bridge you also need to pass the state of the UI components before they can be drawn, which slows everything down and can cause your UI to skip frames instead of keeping the animation smooth.
Dart uses an advanced garbage collection system that quickly handles short-lived objects in memory.
As Flutter rebuilds the widget tree every frame, it throws away the old objects and recreates new objects. In a language such as Java, this would cause issues, but Dart is optimized to handle this very quickly.
Most languages require the use of locks to access shared memory, but Dart can perform its garbage collection most of the time without using locks. This fast garbage collection results in very smooth graphics performance, which greatly enhances our game.
The developer has more control over code execution in Dart due to the way threads are implemented. Because Dart doesn't usually require locks for accessing shared memory, unlike most other languages, we have more control over the execution of the code.
Without locks, we avoid a type of call called a race condition, which can happen when separate threads want access to the shared resource (in this case, memory) and it can't be accessed because some other thread has locked access and the lock has to be released before other threads can access it.
In this section, we have discussed how the features of the Dart language help us to write fast games. In the next section, we will summarize what you will learn throughout the book.
In the following subsections, let's start to take a look at what each chapter will explore.
In the next chapter, Chapter 2, Working with the Flame Engine, we will cover the basics of how to use the Flame engine library to set up a game loop, and how to organize your assets for efficient loading.
It is important to plan ahead so that you have a blueprint to refer to as you progress through your game.
In Chapter 3, Building a Game Design, we will talk about how to plan and design a game using an example that I will refer to throughout the book.
Apart from text-based games, all games have graphics. The graphics are the first thing someone will see when deciding whether to buy or play your game, so it's important for these to look nice if you want to sell your game.
In Chapter 4, Drawing and Animating Graphics, we will show you how to draw graphics on the screen, and how to animate them so they look real. We will also show you how to detect when graphics collide with each other, such as a bullet hitting an enemy, which can be used to trigger another animation, such as the enemy exploding.
All games require some type of input, whether this is touching a screen, pressing a key, or moving a virtual joystick to control a player.
In Chapter 5, Moving the Graphics with Input, we will explain the many methods for controlling the character so that the input and animation are synchronized and feel smooth and responsive.
Sound effects and music play an important part in games to enhance the experience for the player. The background music also plays an important part in any game; as you play the game, the music can change to highlight something important in the game or to change the mood of the game.
In Chapter 6, Playing Sound Effects and Music, we will discuss how to synchronize playing a sound effect in response to a game event, such as playing an explosion sound when a bullet collides with an enemy.
Most games are not played on a single screen and require careful thought about how each level is designed.
In Chapter 7, Designing Your Own Levels, we will explain how to load graphics, sounds, and level data that is needed for the current level, to ensure we don't run into memory or performance issues, which can be a real problem when developing games for low-end devices such as mobile phones.
We will also explain how to make a map that is larger than the physical screen, and how to navigate your player around the screen and scroll the map as the player moves around.
One of the key benefits of using Flutter and Dart is the cross-platform features it has for making the game work across multiple devices. We will discuss this topic in more detail in Chapter 8, Scaling the Game for Web and Desktop.
As we mentioned earlier, graphics are the first thing a user sees so they must look impressive.
In Chapter 9, Implementing Advanced Graphics Effects, we discuss advanced graphical effects and what we can do to make your game look amazing.
We will use particle effects to enhance the existing graphics and make the game really stand out.
We will also discuss how graphical layers can be used to draw graphics more efficiently when there is a lot of animation on the screen.
Games are more fun when they are realistic, which we can achieve with artificial intelligence (AI).
In Chapter 10, Making Intelligent Enemies with AI, we will show you how to make enemies that can move from one location to another, avoiding obstacles and enemies that can hunt you when they see you.
In Chapter 11, Finishing the Game