Game Development Patterns with Godot 4 - Henrique Campos - E-Book

Game Development Patterns with Godot 4 E-Book

Henrique Campos

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Game development demands more than just creativity; it requires code that’s as dynamic and adaptable as the games you dream of creating. Seasoned Godot developer, educator and creator of popular resources like The Essential Guide to Creating Multiplayer Games with Godot 4.0, Henrique Campos introduces you to object-oriented programming design patterns, offering time-tested, reliable solutions to common coding issues. With these patterns, you’ll not only build scalable, maintainable architectures for your games but also gain the confidence to tackle real-world development challenges head-on with Godot's built-in features.
In this hands-on guide, you’ll step into the role of a game mechanics engineer tasked with implementing requests from a fictional game designer, simulating the collaborative nature of real-world game development. Using Godot 4.3, you’ll develop a complete platformer game featuring a playable character, enemies with advanced AI, interactive objects, multiple levels, music, and more. Along the way, you’ll master core programming concepts such as SOLID principles, favor composition over inheritance, and have a solid understanding of object-oriented programming along with the principles behind the design patterns.
By the end of the book, you’ll be able to diagnose and fix pathologies in your code with ease.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 434

Veröffentlichungsjahr: 2025

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Game Development Patterns with Godot 4

Create resilient game systems using industry-standard solutions in Godot

Henrique Campos

Game Development Patterns with Godot 4

Copyright © 2025 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: Neha Pande

Book Project Manager: Arul Viveaun

Senior Editor: Rakhi Patel

Technical Editor: K Bimala Singha

Copy Editor: Safis Editing

Indexer: Rekha Nair

Production Designer: Nilesh Mohite

DevRel Marketing Coordinator: Nivedita Pandey

First published: January 2025

Production reference: 2100225

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83588-028-9

www.packtpub.com

To my Lord and Savior, Jesus Christ, who gave me the strength and faith to dedicate my efforts to writing this book, knowing it will be used for great things. And to my family: Sheila, my mother, Claudio, my father, and Ráisa, my sister, who have always been by my side on my journey in the video game industry. In memory of my uncle Wemerson, who made great investments in my dream. With all my heart.

– Henrique Campos

Contributors

About the author

Henrique “Ludonaut” Campos is an indie game developer and game designer working in the industry for years. Started as a University teacher in 2015 in the Computer Graphics and Artificial Intelligence chairs and working in the GDQuest team from 2018 to 2022, Henrique is also an independent consultant for studios and schools. Under the alias of Ludonaut, Henrique creates game development content on his YouTube channel making games, assets, ebooks, and courses that can be found in his itch.io profile.

Being the author of The Essential Guide to Creating Multiplayer Games with Godot 4.0, Henrique paved the way for Godot users to make incredible shared online experiences while helping them discover the engine's bleeding edge features.

I want to thank everyone who is working to create great open source software such as Godot; you are building a better world. Special thanks to my family and friends, especially Arthur, Luan, and Tumeo for being by my side and believing in my dream. I also want to thank my supporters, who have followed every step of this journey, especially Laurence Bannister and Kyle Szklenski. Lastly, thank you to my brothers in Christ for all the support they’ve given me.

About the reviewers

Jonathan Reeves is a multi-faceted software engineer with more than 6 years of professional experience. He has a wealth of experience, ranging from full-stack development to video game development, and he has a passion for technical education. He’s adept at building engaging user interfaces for both consumer-facing and internal web applications. Beyond the frontend side of things, he has developed a few games and published them on web and mobile platforms. Previous technical works he has worked on are React 18 Design Patterns and Best Practices, 4th edition by Carlos Santana Roldánand React and React Native, 5th edition by Mikhail Sakhniuk and Adam Boduch.

Ryan Hinds is an independent game developer, the founder and CEO of Industrial Llama, and a teaching assistant for courses such as Godot 4 C# Action Adventure: Build your own 2.5D RPG through GameDev.tv. He was born in Alberta, Canada, where he resides with his wife and their daughter. He has recently started reviewing and editing educational books on programming in his free time to help others learn the trade. Currently, he is a student in Advanced Game Development at Bow Valley College in Calgary, Alberta.

Table of Contents

Preface

Part 1: Object-Oriented Design Principles

1

Understanding Object-Oriented Design

Technical requirements

Learning the basics of OOP

Complying with the principles of OOP

Designing games with OOP

Turning your design into an object in Godot Engine

Summary

2

Learning the Four Fundamental Pillars

Technical requirements

Simplifying complex systems with abstraction

Scoping properties and methods with encapsulation

Extending an object’s behaviors with inheritance

Maintaining compatibility with polymorphism

Summary

3

Creating SOLID Design Solutions

Unbloating objects with the SRP

Maintaining and extending objects with the OCP

Ensuring compatibility with the LSP

Creating components with the ISP

Making high-level abstractions with the DIP

Summary

4

Favoring Composition Over Inheritance

Technical requirements

Understanding the composition approach

Creating complex scenes by composing with nodes

Turning a behavior into a component

Making games by composing with scenes

Creating the LootBumpingPig

Summary

Part 2: Basic Design Patterns

5

Maintaining Global States with the Singleton Pattern

Technical requirements

Understanding the Singleton pattern

Spotting use cases of singletons in games

Maintaining players’ data throughout the game states

Playing background music without interruptions

Using third-party APIs and plugins

Accessing the engine’s built-in features

Implementing the Singleton pattern in Godot

Understanding the designer’s request

Creating the score system

Implementing the multi-door teleporting system

Summary

6

Decoupling Objects with the Observer Pattern

Technical requirements

Understanding the Observer pattern

Spotting use cases for the Observer pattern

Implementing the Observer pattern in Godot

Integrating the player’s health interface

Summary

7

Spawning Game Objects with the Factory Pattern

Technical requirements

Understanding the Factory pattern

Spotting use cases for the Factory pattern

Implementing the Factory pattern in Godot

Creating the Node2DFactory class

Using Node2DFactory in our game

Summary

8

Changing Object Behavior with the State Pattern

Technical requirements

Understanding the State pattern

Spotting use cases of the State pattern in games

Implementing the State pattern in Godot

Understanding the designer’s requirements

Implementing an FSM with animations

Handling state-specific behaviors with the State pattern

Summary

9

Designing Actors with the Command Pattern

Technical requirements

Understanding the Command pattern

Spotting use cases for the Command pattern

Using commands such as undo/redo in level editors

Queuing commands in real-time strategy games

Creating strategic encounters in role-player games

Making template behaviors in RPGs

Backtracking actions in tactical RPG battles

Implementing the Command pattern in Godot

Evaluating the game designer’s changes

Creating the BumpingPig commands

Using commands with buttons

Implementing the concrete commands

Mapping the commands to buttons

Designing the Bumping Pig brain

Summary

Part 3: Advanced Design Patterns

10

Implementing AI with the Strategy Pattern

Technical requirements

Understanding the Strategy pattern

Spotting use cases for the Strategy pattern

Implementing the Strategy pattern in Godot

Creating the InteractionStrategy family

Using the target object to provide a strategy

Cleaning up the Brain class with strategy executions

Implementing interaction strategies

Summary

11

Creating a Power-Up System with the Decorator Pattern

Technical requirements

Understanding the Decorator pattern

Spotting use cases for the Decorator pattern

Implementing the Decorator pattern in Godot Engine

Turning properties into the Stats class

Creating our StatsDecorator class

Wrapping Stats with the power-ups Singleton

Using Diamond objects to add power-ups

Summary

12

Cross-Fading Transitions with the Service Locator Pattern

Technical requirements

Understanding the Service Locator pattern

Spotting use cases for the Service Locator pattern

Implementing the Service Locator pattern in Godot Engine

Creating the BackgroundMusic Service Locator

Using the BackgroundMusic Service Locator

Summary

13

Improving Game Feel with the Event Queue Pattern

Technical requirements

Understanding the Event Queue pattern

Spotting use cases for the Event Queue pattern

Implementing the Event Queue pattern in Godot

Storing input events with an input buffer

Buffering and processing jumps

Summary

Index

Other Books You May Enjoy

Preface

Hello there! I’m Henrique Campos, also known as Ludonaut, and in this book, we will talk about a topic that always intrigues me: design patterns. Specifically, in this book, we will talk about object-oriented programming design patterns. The idea behind this is that there are numerous problems regarding design that are common, so instead of reinventing the wheel, we can stand on the shoulders of giants and rely on tested, time-proven solutions. But in doing so, we are going to take a non-conventional path. You will learn the following from this book:

Create reusable and scalable code that follows SOLID principlesIdentify common game development issues and apply industry-standard solutionsUnderstand feature requests and how to turn them into concrete solutions leveraging design patternsAnalyze game development pathologies to figure out underlying issuesArchitect reliable systems that are understandable, intuitive, and scalableStructure professional, collaborative game systems that are easy to maintain

We will use our imagination by role-playing a game mechanics engineer who is responsible for implementing requests from a fictional game designer. This allows us to work in a similar context to real life, where a designer responsible for the creative direction of a game, comes with game design requests that a programmer should implement. In this process, we will create a complete platformer game with a player, an enemy with complex artificial intelligence, interactive objects, multiple levels, music, and more.

By the end of this book, you will have a solid knowledge of how to create reliable architectures for your game’s code bases that you can scale and reuse knowing exactly what its points of pressure are and how to solve potential problems. You will also understand that design patterns should not be used as an initial approach to implementing features; instead, they are used as solutions for problems that arise as we develop our games. In this process, you will learn refactoring techniques that will save you time and energy.

As a friend of mine says: an amateur knows how to create new code, and a professional knows how to fix old code. In that sense, the skills you will learn from this book will help you avoid the urge to make things from scratch and instead deal with ugly and messy situations, thriving through them and leaving a trail of elegant and scalable solutions.

Throughout the book, we will use Godot Engine 4.3, by the time of writing, the latest version of the rising star open source project that has been getting the industry’s eyes. To make the onboarding easy, we will use the built-in text editor and GDScript as the main tools. Godot has many built-in features that help us implement the design patterns we are going to see. In some cases, such as the Observer pattern, Godot provides the implementation and all we have to do is use it, but we must understand the principles behind it.

Who this book is for

This book is for anyone with sufficient knowledge to understand what variables and methods are. As we introduce basic programming and object-oriented programming concepts, most of the content in the book can be used by intermediate to advanced programmers. People who have experience with GDScript and the Godot Engine editor will take the most out of this book as the main focus is to present the design patterns themselves. People with no programming background will have trouble understanding the core concepts and how each pattern helps to solve specific issues.

The three main skills our audience must have in order to make great use of this book are as follows:

Understanding the nodes and resources philosophy behind Godot Engine’s designBasic knowledge of the GDScript language’s syntaxExperience with programming concepts such as functions, variables, constants, algorithms, and procedures

To summarize it all, if you have already made one or two games with Godot Engine or similar applications, you will be able to understand the concepts presented in this book and the problems that we face throughout the process of making a game. Understanding these problems is fundamental to understanding the value of using the design patterns we will introduce in this book. But if you have good abstract thinking and can intuitively understand how one approach can generate issues as projects scale, then you will also be able to engage with this book’s value proposition.

What this book covers

Chapter 1, Understanding Object-Oriented Design, explains the philosophy behind writing programs from an object-oriented perspective.

Chapter 2, Learning the Four Fundamental Pillars, discusses the tools object-oriented programming provides to write object-oriented code.

Chapter 3, Creating SOLID Design Solutions, guides you through five core principles of writing good, reusable, and scalable object-oriented code.

Chapter 4, Favoring Composition Over Inheritance, explains that inheritance is a powerful but dangerous tool in object-oriented programming, so we must use it responsibly. In this chapter, you will explore the issues behind inheritance and the composition alternative to achieve code reusability.

Chapter 5, Maintaining Global States with the Singleton Pattern, begins implementing the Singleton pattern for a common issue in game development: global data that multiple objects should have access to.

Chapter 6, Decoupling Objects with the Observer Pattern, discusses coupling, which is a major issue in programming, but it’s unavoidable. But with the Observer pattern, we can make objects communicate without coupling them by using a notification system.

Chapter 7, Spawning Game Objects with the Factory Pattern, covers creating new objects in the game world, which is a skill every game developer needs to master. Using the Factory Pattern can help you do that in a reliable and reusable fashion.

Chapter 8, Changing Object Behavior with the State Pattern, discusses handling object states, which can lead to a chaotic monolith code base that handles state machines and multiple states in a single class. The State pattern is a way to extract this code from the context class with the double benefit of encapsulating each state as an independent object.

Chapter 9, Designing Actors with the Command Pattern, explains that a method, or function, doesn’t leave footprints when called, and this can be an issue. By turning requests into objects, we can store them in memory, store their parameters, pass them around, delay their execution, queue them, execute them in a specific order, and even undo them, and all that is possible using the Command pattern.

Chapter 10, Implementing AI with the Strategy Pattern, explains that using conditional statements to alter the behavior of your code based on specific parameters may not be scalable. The Strategy pattern proposes that, instead, we use objects called strategies that perform different behaviors and adapt the context in real time by passing these objects.

Chapter 11, Creating a Power-Up System with the Decorator Pattern, explores wrapping objects within objects, which is a common practice in programming. The Decorator pattern proposes that we can wrap objects within objects of the same type, allowing us to add new functionalities to them in real time. With this in mind, we create an interesting power-up system for our project, wrapping objects with power-ups.

Chapter 12, Cross-Fading Transitions with the Service Locator Pattern, discusses one way to protect our code from coupling, which is by using a mediator object as an interface to interact with other parts of the game. The Service Locator pattern allows us to perform procedures, such as changing the game music, without leaking implementation and maintenance details on user classes.

Chapter 13, Improving Game Feel with the Event Queue Pattern, explores situations when we need to store events such as keystrokes to be handled in the future. An example is checking whether the player has jumped while in mid-air in the last few milliseconds so that the character performs a jump when they land on the ground. We can achieve this kind of functionality with the Event Queue Pattern.

To get the most out of this book

In order to fully engage with the exercises and examples provided in this book, you will need to download and install Godot Engine 4.3. This version of the engine introduces key features and updates that are essential for understanding and implementing the techniques we cover. Whether you’re new to Godot or have experience with earlier versions, it’s important to work with version 4.3 to ensure compatibility with the projects and concepts discussed throughout the book.

You can easily download Godot Engine 4.3 from the official website at godotengine.org. The installation process is straightforward, and the engine is available for Windows, macOS, and Linux. Be sure to follow the instructions for your operating system, and once it is installed, familiarize yourself with the interface. By using the same tools and environment that we explore in this book, you will have the best learning experience and will be able to follow along with the code examples smoothly.

Software/hardware covered in the book

Operating system requirements

Godot Engine 4.3

Windows, macOS, or Linux

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Game-Development-Patterns-with-Godot-4. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Add a new AudioStreamPlayer node as a child of the BackgroundMusic node.”

A block of code is set as follows:

extends Area2D class_name AmbienceArea2D @export var background_music: AudioStream var previous_background_music: AudioStream

Any command-line input or output is written as follows:

$ mkdir css $ cd css

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Then, drag and drop a piece of cool music to the Background Music property on the Inspector.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Game Development Patterns with Godot 4, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/978-1-83588-028-9

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Object-Oriented Design Principles

Object-oriented programming is a programming paradigm with its own approach and way of thinking. To design systems using the tools that object-oriented programming offers, we need to understand what we have at our disposal and how to take the most out of it by following good principles. In this part, you will be introduced to the general philosophy behind programming, object-oriented programming, the four major instruments we use in object-oriented programming, the SOLID principles, and how to favor composition over inheritance and avoid misusing inheritance, a major critique that this paradigm receives from professionals across the industry.

This part includes the following chapters:

Chapter 1, Understanding Object-Oriented DesignChapter 2, Learning the Four Fundamental PillarsChapter 3, Creating SOLID Design SolutionsChapter 4, Favoring Composition Over Inheritance