GDScript Examples Tutorial – Complete Guide

Welcome to our journey into the world of GDScript! In this comprehensive tutorial, we are set to explore the workings of GDScript together, through fun and relatable examples.

Whether you’re a beginner taking your first steps into coding, or you’re an experienced programmer exploring new realms, this guide is created with the intention of making GDScript both accessible and engaging for you.

What is GDScript?

GDScript is a high-level, dynamically typed programming language mostly used in the Godot Game Engine. It was designed with the goal of being highly integrated with the engine, providing a smoother user experience than more complex languages like C# or C++.

What is GDScript used for?

Designed specifically for Godot, GDScript is used to script the game logic within the engine. It covers every aspect of game development, from controlling character animation to handling user input.

Why Learn GDScript

As a Godot-specific language, mastering GDScript means unlocking the full power of the Godot Engine. Since it mirrors Python’s syntax, GDScript is relatively easy to learn and it’s perfect for scripting quick gameplay prototipes.

Furthermore, GDScript’s tight integration with Godot also means you have an easier time debugging your projects, leading to a smoother game development journey.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Syntax of GDScript

Let’s start by exploring the basic syntax of GDScript to build your familiarity with the language. We’ll cover variables, functions, loops, and conditional statements.

Variables in GDScript

In GDScript, declaring a variable is straightforward. Here’s how:

var my_var = 10

You can also specify the type of the variable while declaring it:

var my_var: int = 10

Functions in GDScript

Function declaration in GDScript is similar to that in Python. Look at the following example:

func my_func():
  print("Hello, Zenva!")

To call a function, you simply type its name followed by parentheses:

my_func()

You can pass parameters to your functions as well:

func greet(name):
  print("Hello, " + name + "!")

Loops in GDScript

Loops in GDScript are quite simple, here is a basic for loop:

var my_array = [1, 2, 3, 4, 5]
for i in my_array:
  print(i)

We also have while loops:

var count = 0
while count < 5:
  print(count)
  count += 1

Conditional Statements in GDScript

As in most programming languages, GDScript also offers if-else statements. Here’s an example:

var my_var = 10
if my_var > 5:
  print("It's greater than 5")
else:
  print("It's not greater than 5")

Of course, we can expand this with elif for more conditions:

var my_var = 10
if my_var > 10:
  print("It's greater than 10")
elif my_var == 10:
  print("It equals 10")
else:
  print("It's less than 10")

GDScript and OOP – Define a Class

GDScript is an object-oriented language which makes it easy for us to define classes, create objects, and utilize inheritance. Let’s start by defining a class!

In GDScript, each file is treated as a separate class. The name of the class is the name of the file. Here’s an example of a class definition:

class_name MyFirstClass


func say_hello():
    print("Hello, world!")

Creating Instances

Now that we have the class defined, let’s create an instance of the class:

var my_instance = MyFirstClass.new()

my_instance.say_hello()

The .new() method is used to create an instance of the class, and the instance’s methods can be called just like any other object.

Inheritance in GDScript

Inheritance helps us re-use and organize code in a better way. In GDScript, you can easily employ single inheritance by using the ‘extends’ keyword:

extends MyFirstClass

Now, this class has all properties and methods of MyFirstClass. You can override methods from the parent, or add new ones to extend its functionality:

extends MyFirstClass


func welcome():
    print("Welcome to Zenva!")

Calling the welcome function here will print out the custom message from the new class.

Utility Functions

GDScript provides a set of built-in utility functions to make life easier. Let’s see some examples:

var max_num = max(10, 20)  # returns 20, the maximum of the two


var my_string = str(10)  # converts the integer 10 to a string


var is_inf = is_inf(10.0 / 0.0)  # checks if the value is positive or negative infinity

These are just a few of the utility methods available. With these basic concepts of GDScript, you can now start exploring more complex game development tasks in the Godot engine!

Understanding Signals in GDScript

Signals are a crucial aspect to Godot and GDScript, helping communication between nodes. You can declare a signal in your class and emit it when needed. Look at the following example:

signal my_signal

func emit_my_signal():
    emit_signal("my_signal")

Now, any other node in the scene can connect to this signal and react accordingly. This is done by calling the below code from the node that wants to listen to the signal:

my_node.connect("my_signal", self, "on_my_signal")

# This is the function that'll get called when the signal is emitted
func on_my_signal():
    print("My signal has been emitted!")

Predefined Functions You Should Know

GDScript has many predefined functions that you’ll often use in your game development journey, and they’re very critical when it comes to life-cycle management of your nodes and scenes. Here are some important ones:

_ready() – This is called when the node, and all of its children, have entered the scene tree. This is used to initialize any scripting variables, or connections between nodes.

func _ready():
    print("_ready function called!")

_process(delta) – This is called every frame before drawing. ‘Delta’ is the time since the last frame was drawn. This is useful for applying constant changes, like movement or timers.

func _process(delta):
    print("_process function called!")

_physics_process(delta) – Similar to _process, but this is called in sync with the physics engine. Use it for things involving the physics engine, like character movement.

func _physics_process(delta):
    print("_physics_process function called!")

Accessing and Changing Node Properties

You can easily access and modify the properties of your nodes in GDScript.

# Accessing the position of the node
var my_node_position = self.position

# Setting the position of the node
self.position = Vector2(10, 20)

GDScript and Game Design

Finally, to showcase how GDScript integrates into game design within Godot Engine, let’s create a simple 2D game character that can move and jump.

extends KinematicBody2D

var speed = 200
var jump_force = -500
var gravity = 1200

var velocity = Vector2()

func _physics_process(delta):
    velocity.x = 0

    if Input.is_action_pressed("ui_right"):
        velocity.x += speed
    if Input.is_action_pressed("ui_left"):
        velocity.x -= speed
    if Input.is_action_just_pressed("ui_up") and is_on_floor():
        velocity.y = jump_force

    velocity.y += gravity * delta

    move_and_slide(velocity, Vector2.UP)

Here, we have a 2D Kinematic Body character that can move left or right with the arrow keys, and also jump when the up arrow key is pressed.

And this overview should give you a good grasp of writing GDScript for Godot, and you’re all set to dive deeper into the game development journey at Zenva!

Now that you’ve built a foundation in GDScript, it’s time to delve deeper and really explore everything that the Godot Engine has to offer. The path of game development is an exciting one, full of creativity, problem-solving and continual learning. And remember – you’ve just started climbing the hill, the view gets even more beautiful as you ascend.

Consider checking out the Godot Game Development Mini-Degree offered by Zenva Academy. This comprehensive course provides a wide coverage on numerous aspects of game development, including assets utilization, combat systems, UI systems, and so much more. You’ll even have the opportunity to work on projects that you can add to your portfolio! The curriculum here is flexible, allowing you learn at your own pace, and the content is continually updated so you’re always learning the current industry practices.

Plus, you can explore our broader collection of Godot courses to further enhance your game development skills or even dive into other realms of programming and AI. With over 250 supported courses, Zenva Academy is continuously striving to be your partner in growth – from beginner to professional.

Conclusion

We’ve opened the gateway to the compelling universe of game development using GDScript and Godot Engine. Hopefully, this guide has made GDScript more approachable and sparked your curiosity to explore it further. Remember, armed with knowledge, creativity, and persistence, the possibilities are relentless – you can create your dream world within the boundary of your game.

The transformative journey of game development awaits you. Whether you’re a beginner exploring the world of coding, or a skilled developer, Zenva Academy has a treasure trove of resources for everyone. Check out our Godot Game Development Mini-Degree and embark on this fulfilling journey of creative coding and engineering with us!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.