Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Learning GDScript by Developing a Game with Godot 4: A fun introduction to programming in GDScript 2.0 and game development using the Godot Engine
Learning GDScript by Developing a Game with Godot 4: A fun introduction to programming in GDScript 2.0 and game development using the Godot Engine
Learning GDScript by Developing a Game with Godot 4: A fun introduction to programming in GDScript 2.0 and game development using the Godot Engine
Ebook902 pages5 hours

Learning GDScript by Developing a Game with Godot 4: A fun introduction to programming in GDScript 2.0 and game development using the Godot Engine

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateMay 17, 2024
ISBN9781801812498
Learning GDScript by Developing a Game with Godot 4: A fun introduction to programming in GDScript 2.0 and game development using the Godot Engine

Related to Learning GDScript by Developing a Game with Godot 4

Related ebooks

Programming For You

View More

Reviews for Learning GDScript by Developing a Game with Godot 4

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Learning GDScript by Developing a Game with Godot 4 - Sander Vanhove

    Cover.jpgPackt Logo

    Learning GDScript by Developing a Game with Godot 4

    Copyright © 2024 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: Kaustubh Manglurkar

    Book Project Manager: Sonam Pandey

    Senior Editor: Anuradha Joglekar

    Technical Editor: K Bimala Singha

    Copy Editor: Safis Editing

    Proofreader: Anuradha Joglekar

    Indexer: Subalakshmi Govindhan

    Production Designer: Gokul Raj S.T

    DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey

    First published: May 2024

    Production reference: 1170424

    Published by

    Packt Publishing Ltd.

    Grosvenor House

    11 St Paul’s Square

    Birmingham

    B3 1RB, UK

    ISBN 978-1-80461-698-7

    www.packtpub.com

    To all new Godot Engine users, may your games be great!

    - Sander Vanhove

    Contributors

    About the author

    Sander Vanhove is a lead game developer and technical artist at Studio Tolima, a Brussels-based studio working on its first commercial game, Koira.

    Creating little games for his friends from the age of 14 led him to pursue a master’s degree in computer science, after which he worked as a data analyst for several years.

    In 2018, he decided to give the Godot Engine a try and never looked back. With a mountain of jam games, uncountable game experiments, and a few small commercial game releases under his belt, he finally took the plunge of working full time at a game studio, the aforementioned Studio Tolima.

    He can always be found working on that next project, learning new game development techniques, or trying to teach people how to use the Godot Engine.

    I want to thank my parents, Martine and Gerrit, and close friends who believed in me and this project and would relentlessly inquire about its progress.

    About the reviewers

    Jesse Glover is a seasoned software consultant with a comprehensive background in both backend and frontend development, specializing in Salesforce and ServiceNow development and administration. Jesse has honed his skills in various technical domains with a particular focus on modern frontend frameworks and tools.

    In addition to his professional accomplishments, Jesse is passionate about sharing his knowledge and expertise through his YouTube channel, GameDevMadeEasy, where he creates educational content on game and software development.

    Jesse was also the author of Unity 2018 Augmented Reality Projects, which is available on the Packt website.

    Ludovic de Saint-Viance, known on the internet as theLudovyc, is a senior developer who likes to use Godot in his free time. He has been creating different projects (you can find them on his Itch.io or GitHub pages) for 6 years. Also, he was the admin of a French Discord server about Godot: Espace Godot.

    I thank Nikita Raghani from Packt, who invited me to review this book, and my manager, Sonam Pandey. I am also very thankful to the author of this book, Sander, and Packt for being part of this incredible journey. To quote Sander, I want to respect Packt rules, but it feels strange to introduce myself like on a Wikipedia page. If someone reads those lines to the end, my favorite pizza is the one with pineapple.

    Table of Contents

    Preface

    Part 1: Learning How to Program

    1

    Setting Up the Environment

    Technical requirements

    Godot game engine and open-source software

    Some background on the engine

    What is open-source software?

    Getting and preparing Godot

    Downloading the engine

    Creating a new project

    Light mode

    Creating the main scene

    A brief UI overview

    Writing our first script

    The Godot Engine Documentation

    Join our community!

    Summary

    Quiz time

    2

    Getting Familiar with Variables and Control Flow

    Technical requirements

    What are variables?

    Variables – Drawers in a filing cabinet full of data

    Naming variables

    Variables in GDScript

    Printing out variables

    Changing a variable’s value

    Mathematical operators

    Other assignment operators

    Data types – Integers, floats, and strings

    Integers

    Floats

    Strings

    What are constants?

    Constants in GDScript

    Magic numbers

    Creating new scenes

    Getting started with control flow

    The if statement

    The if-else statement

    The elif statement

    Commenting in code

    Indentation

    Boolean logic

    The match statement

    The ternary-if statement

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    3

    Grouping Information in Arrays, Loops, and Dictionaries

    Technical requirements

    Arrays

    Creating an array

    Accessing values

    Accessing elements backward

    Changing the elements of an array

    Data types in arrays

    Strings are secretly arrays

    Manipulating arrays

    Don’t be scared of errors or warnings

    Loops

    For loops

    While loops

    Continuing or breaking a loop

    Dictionaries

    Creating a dictionary

    Data types in dictionaries

    Accessing and changing values

    Creating a new key-value pair

    Useful functions

    Looping through dictionaries

    Nested loops

    Null

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    4

    Bringing Structure with Methods and Classes

    Technical requirements

    Methods are reusable bits of code

    What is a function?

    Defining a function

    Naming a function

    The return keyword

    The pass keyword

    Optional parameters

    Classes group code and data together

    Defining a class

    Instancing a class

    Naming a class

    Extending a class

    Each script is a class!

    When are certain variables available?

    The scope of a function

    Types help us to know how to use a variable

    What is type hinting?

    Type hinting variables

    Type hinting arrays

    Learning about the Variant type

    Type hinting function parameters

    Type hinting function returns

    Using void as a function return

    Inferred types

    null can be any type

    Autocompletion

    Using type hinting for named classes

    Performance

    Editor adding type hints

    OOP primer

    Inheritance

    Abstraction

    Encapsulation

    Polymorphism

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    5

    How and Why to Keep Your Code Clean

    Technical requirements

    Back to naming things

    Naming conventions

    General naming tips

    Public and private class members

    Make short functions

    DRY

    Do one thing (KISS)

    Defensive programming

    Programming style guides

    White spacing

    Blank lines

    Line length

    Utilizing the documentation

    Accessing a class’s documentation

    Directly accessing a function or variable’s documentation

    Going to the definition of a function or variable

    Searching the documentation

    Accessing the online documentation

    Summary

    Quiz time

    Part 2: Making a Game in Godot Engine

    6

    Creating a World of Your Own in Godot

    Technical requirements

    Game design

    Genre

    Mechanics

    Story

    Creating a player character

    Adding a sprite

    Displaying health

    Manipulating nodes in the editor

    Creating the player script

    Referencing nodes in a script

    Caching node references

    Trying out the player script

    Exporting variables to the editor

    Setters and getters

    Changing values while the game is running

    Different types of exported variables

    Creating a little world

    Changing the background color

    Adding Polygon2D boulders

    Node drawing order

    Creating an outer wall

    Getting creative

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    7

    Making the Character Move

    Technical requirements

    Vector math refresher

    The 2D coordinate system

    What is a vector?

    Scaling vectors

    Adding and subtracting vectors

    More vector operations

    Moving the player character

    Changing the current player node

    Applying forces to the player

    Process and physics process functions

    Mapping input

    Using the input

    Smoothing out the movement

    Debugging a running game

    Breakpoints

    Remote tree

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    8

    Splitting and Reusing Scenes

    Technical requirements

    Saving a branch as a new scene

    Creating a separate player scene

    The root node of a scene

    Using saved scenes

    Organizing scene files

    Additional exercises – Sharepening the axe

    Summary

    Quiz time

    9

    Cameras, Collisions, and Collectibles

    Technical requirements

    Making a camera that follows the player

    Setting up a basic camera

    Adding drag margins

    Making the camera look ahead

    Smoothing out the look ahead

    Collisions

    The different physics bodies

    The Area2D node

    Adding a collision shape to the player node

    Creating static bodies for the boulders

    Creating static bodies for the walls

    Creating collectibles

    Creating the base collectible scene

    Inheriting from a base scene

    Connecting to a signal

    Writing the code for collectibles

    Using collision layers and masks

    Your turn!

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    10

    Creating Menus, Making Enemies, and Using Autoloads

    Technical requirements

    Creating a menu

    Control nodes

    Creating a basic start menu

    Setting the main scene

    Making enemies

    Constructing the base scene

    Navigating enemies

    Writing the enemy script

    Damaging the player in a collision

    Spawning enemies and collectibles

    Making a Game Over screen

    Shooting projectiles

    Creating the base scene

    Writing the logic of the projectile

    Spawning projectiles

    Storing highscores in autoloads

    Using an autoload

    Creating a HighscoreManager autoload

    Autoloads in the remote tree

    Adding a UI in the main menu and game scene

    Using the highscore in the main menu

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    11

    Playing Together with Multiplayer

    Technical requirements

    A crash course in computer networking

    What is a Transport Layer?

    What is an Application Layer?

    Networking in Godot Engine

    Learning about IP addresses

    Using port numbers

    Setting up the base networking code

    Creating the client-server connection

    Adding UI

    Running multiple debug instances at the same time

    Synchronizing different clients

    Updating the player scene for multiplayer

    Synchronizing EntitySpawner

    Synchronizing the enemy and collectibles

    Synchronizing the projectile

    Fixing the timer and end game

    Synchronizing the timer

    Synchronizing the end of the game

    Running the game on multiple computers

    Showing the IP address of the server

    Connecting from another computer

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    Part 3: Deepening Our Knowledge

    12

    Exporting to Multiple Platforms

    Technical requirements

    Exporting for Windows, Mac, and Linux

    Downloading the export template

    Making the actual exports of the game

    Uploading our game to Itch.io

    What is Itch.io?

    Exporting our game to the web

    Uploading to Itch.io

    Exporting our game to other platforms

    Mobile platforms

    Consoles

    Summary

    Quiz time

    13

    OOP Continued and Advanced Topics

    Technical requirements

    The super keyword

    Static variables and functions

    Enumerations

    Lambda functions

    Creating a lambda function

    Where to use lambda functions

    Passing parameters by value or reference

    Passing by value

    Passing by reference

    The @tool annotation

    Summary

    Quiz time

    14

    Advanced Programming Patterns

    Technical requirements

    What are programming patterns?

    Exploring the Event Bus

    The problem

    The solution

    Understanding Object Pooling

    The problem

    The solution

    Implementing the Object Pool in our game

    Working with State Machines

    The problem

    The solution

    An example state

    Additional exercises – Sharpening the axe

    Summary

    Quiz time

    15

    Using the File System

    Technical requirements

    What is the file system?

    File paths

    User path

    Creating a save system

    Writing data to the disk

    Reading data from disk

    Preparing the save manager for use in the game

    Adjusting the game to use the save manager

    Having a look at the save file

    Summary

    Quiz time

    16

    What Next?

    Ideas for your next projects

    Starting a new project

    Extending the survivor-like game

    Creating another game

    Free game assets

    Learning about new topics

    Following specific tutorials

    Reading more books

    Reading the Godot Engine documentation

    Looking at the game code of other people’s projects

    Joining the community

    Joining the Forum, Discord, Reddit, or any other platform

    Contributing to the Godot Engine project

    Joining a game jam

    Goodbyes

    Index

    Other Books You May Enjoy

    Preface

    Godot Engine is the most popular free open-source game engine on the market. With the advent of Godot 4.0 and the release of many hit games made in Godot, such as Dome Keeper, Brotato, and Case of the Golden Idol, this popularity only grew. There is no better time to learn how to use this wonderful game development tool than now.

    Learning how to program and use a new game engine can be a daunting task. However, this book will guide you step by step through all the aspects of creating your own game from scratch, from the basics of writing our first scripts in GDScript to more advanced topics.

    We’ll learn how to program in GDScript, the custom language of the Godot Engine, which is easy to learn yet very capable and performant for game development. Then, we’ll go over all the ins and outs of the engine’s intuitive graphical interface and discover everything about its flexible node-based approach to game development.

    Who this book is for

    This book is for programmers, game designers, game developers, and game artists who want to start creating games in Godot 4. If you’re new to coding or game development, looking for a new creative outlet, and want to give Godot 4 and GDScript 2.0 a try, this book is for you. While no prior knowledge of programming or Godot is required, this book gradually introduces more complex concepts as you advance through the chapters.

    What this book covers

    Chapter 1

    , Setting Up the Environment, starts off the book by setting up everything we need to create games in the Godot Engine and gives a brief overview of the engine and how to write scripts.

    Chapter 2

    , Getting Familiar with Variables and Control Flow, explains the major concepts of what variables are and how we can store data within them. From here, we go over different control flows that help us make decisions during the execution of our game.

    Chapter 3

    , Grouping Information in Arrays, Loops, and Dictionaries, teaches about two new data types: arrays and dictionaries. These will help us group data in a more structured format. Along the way, we will learn about the two different kinds of loops with which we can loop over different sets of data.

    Chapter 4

    , Bringing Structure with Methods and Classes, delves into writing reusable pieces of code using methods and how to structure variables and methods into classes.

    Chapter 5

    , How and Why to Keep Your Code Clean, introduces many concepts around writing clean code, which will help us create code that is reusable and understandable by others as well as ourselves.

    Chapter 6

    , Creating a World of Your Own in Godot, will kick off our own game project. We’ll start by defining what kind of game we will be making and progress to making the base of a player character and the environment in which they will be moving around.

    Chapter 7

    , Making the Character Move, offers a refresher on vector math, which is integral to moving entities around in two-dimensional space. Then, we’ll write the physics code to make our layer character move and go into debugging the game while it is running.

    Chapter 8

    , Splitting and Reusing Scenes, shows how we can easily split up our game into multiple smaller scenes that are easier to manage and maintain, followed by how we can organize all the scene and script files in tidy folders within the project.

    Chapter 9

    , Cameras, Collisions, and Collectibles, starts by making a smooth camera that will follow the player character without making the real-life player nauseous. After this, we’ll move on to handling collisions with the terrain and creating collectible items.

    Chapter 10

    , Creating Menus, Making Enemies, and Using Autoloads, finishes up our single-player game by teaching us about the menu system of the Godot Engine, followed by the creation of enemies that can navigate through the world and projectiles with which the player can shoot these enemies. We conclude this chapter with an introduction to autoloads, with which we can store the high score.

    Chapter 11

    , Playing Together with Multiplayer, converts our single-player experience into a multiplayer one. We start with a crash course in computer networking. After this, we will learn about MultiplayerSpawner and MultiplayerSynchronizer to be able to play our game with others over a network.

    Chapter 12

    , Exporting to Multiple Platforms, shows how we can export the game for different platforms such as Windows, macOS, Linux, and even the web. We will conclude the chapter by uploading our game to Itch.io, a popular platform for indie games.

    Chapter 13

    , OOP Continued and Advanced Topics, introduces the more advanced object-oriented programming (OOP) topics such as the super keyword, static variables, enumerations, lambda functions, the different ways of passing values to methods, and the tool keyword.

    Chapter 14

    , Advanced Programming Patterns, gives us a basis for programming patterns and explores the Event Bus, Object Pool, and State Machine patterns so that we can use them in our next project.

    Chapter 15

    , Using the File System, introduces the file system of the Godot Engine and shows us how we can save and load data in our game.

    Chapter 16

    , What Next?, leaves us with some last techniques and resources to start the next game project as well as introduce the game development community we can be part of.

    To get the most out of this book

    You don’t need any prior knowledge about programming or game development. The only prerequisite is that you are open to learning and willing to improve. During the book, I propose multiple experiments you could do and have included quizzes to test your knowledge. It’s important that you take the time to do these so that the knowledge gets cemented in your brain.

    We’ll cover how to download and set up the Godot Engine in the first chapter of this book but you could already download Godot 4.2.1 or later if you’re feeling impatient. All the examples in the book were tested on Godot 4.2.1 but should work in future versions too.

    The Godot Engine is a very light piece of software that easily runs on older, outdated hardware but it doesn’t hurt to check out the minimum specifications and make sure your computer is able to meet them: https://docs.godotengine.org/en/stable/about/system_requirements.html

    .

    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/Learning-GDScript-by-Developing-a-Game-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: "In Chapter 1

    , we learned to write code with the _ready method of a node."

    A block of code is set as follows:

    func deal_damage(amount: float) -> void:

       player_health -= amount

    func heal(amount: float) -> void:

       player_health += amount

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    func minimum(number1, number2):

       if number1 < number2:

          

    return number1

     

       else:

          

    return number2

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

    unzip Godot_v4.2.1-stable_linux.x86_64.zip -d Godot

    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: You can access the user:// folder for a given project by opening up the Project menu and choosing Open User Data Folder.

    Containers

    We call an array a container because we can store and retrieve pieces of data of other data types within them, like integers, strings, booleans, and such. An array contains other data.

    Containers structure other data so it is easier to work with.

    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 Learning GDScript by developing a game 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

    Download a free PDF copy of this book

    https://packt.link/free-ebook/978-1-80461-698-7

    Submit your proof of purchase

    That’s it! We’ll send your free PDF and other benefits to your email directly

    Part 1:Learning How to Program

    In this part, we’ll start off by downloading the free and open-source Godot Engine and setting up the environment in which we will be developing our very own game from scratch. Before we come on to creating a game, though, we’ll build strong fundamentals in programming using the GDScript programming language.

    By the end of this part, you will know all about variables, control flows, different data and container types, methods, and classes. We will conclude this part with a chapter on clean coding.

    This part has the following chapters:

    Chapter 1

    , Setting Up the Environment

    Chapter 2

    , Getting Familiar with Variables and Control Flow

    Chapter 3

    , Grouping Information in Arrays, Loops, and Dictionaries

    Chapter 4

    , Bringing Structure with Methods and Classes

    Chapter 5

    , How and Why to Keep Your Code Clean

    1

    Setting Up the Environment

    Game development is becoming more accessible as game engines become more powerful. Tools and pipelines that were only available to big companies and wealthy individuals are now freely available to everyone with a computer. Anyone can feel the satisfaction of creating their own game and having others play it.

    This is exactly what we are going to achieve in this book. We will go from knowing absolutely nothing about programming or developing games to creating our very first game and even a little beyond.

    During the first part of this book, we will learn all about setting up Godot and programming. This might be a little more abstract, but I’ll try to give clear examples and keep you engaged with exercises and experiments you can do for yourself.

    The second part of this book will be way more practical as we will dive neck-deep into creating our very own video game! We’ll learn how to use the Godot editor to create interesting game scenes and scenarios.

    In the last part of this book, we’ll take our programming skills to the next level and learn all about advanced topics, such as more powerful concepts, programming patterns, the filesystem, and much more.

    But before we get there, nothing is more satisfying than starting a new project! It represents a blank slate with endless possibilities. By the end of this chapter, we’ll have created our very own blank slate and written our first lines of code. But first, I’d like to take some time to introduce the Godot game engine and open-source software in general.

    In this chapter, we’re going to cover the following main topics:

    Godot Engine and open-source software

    Downloading the engine from the official website

    Creating our first project

    How to join the community

    Technical requirements

    As this book aims to get you from knowing nothing about programming and game development to an intermediate level, there are no technical requirements. So, instead, I’ll guide you through all (or at least most) of the steps required for creating games.

    Example project and code

    You can find the example project and code for this book in this book’s GitHub repository: https://github.com/PacktPublishing/Learning-GDScript-by-Developing-a-Game-with-Godot-4/tree/main/chapter01

    .

    Godot game engine and open-source software

    We’ll be using the Godot game engine, which I presume you already know exists as this is a book specifically about that engine. But let me give you some more insight into its history and what open-source means.

    Some background on the engine

    Godot Engine is a piece of open-source software that lets people from all experience levels and walks of life create games. The project was started in 2007 by Juan Linietsky and Ariel Manzur as an in-house engine for several Argentinian game studios. In late 2014, the engine got open-sourced, giving everyone free access to the code. Since then, it has gained lots of traction and is currently one of the most used game engines on the market. Many commercial games have been released or are under development using the engine. Examples of released games are Brotato, Dome Keeper, Case of the Golden Idol, and Cassette Beasts.

    For those of you wondering, yes,

    Enjoying the preview?
    Page 1 of 1