0% found this document useful (0 votes)
13 views69 pages

Mastering GD Script Free Ver2

Uploaded by

Joe Waters
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views69 pages

Mastering GD Script Free Ver2

Uploaded by

Joe Waters
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Mastering Godot

Title: Mastering Godot

Author: Marijo Trkulja

Edition: first, 2020

You are reading the expanded free version of the book "Mastering

Godot". Only for newsgroup members.

Rights to translate (only for GD Script book) from English into

other languages can be purchased. You may sell the translated

book on terms that are accepted when you purchase the

translation right. For example, for the first thousand copies sold,

you pay 9% of the book's sales price. If your translation of the

book is accepted, you receive 9% of your sales revenue (valid for

the first thousand copies).

More information by email at: letray2@yahoo.com

subject: Can I obtain translation rights for GD Script book


Preface
New book by the author of the well-known titles on Godot game

engine and GD Script such as GD Script, Making games with GD

Script, Autonomous Cars, etc.

The book uses the MTH method for learning and is written for

both beginner and experienced game developers. Beginners are

advised to read a book from the beginning, and game developers to

use it as a reminder and troubleshooting guide.


Table of Contents
Preface..................................................................................................................4
New project creation............................................................................................1
Create 2D scene...............................................................................................1
GD Script.........................................................................................................1
Class 2D Node......................................................................................................2
Properties:........................................................................................................2
Position.......................................................................................................2
Rotation.......................................................................................................3
Scale............................................................................................................4
Transform....................................................................................................5
Global position............................................................................................6
Global rotation............................................................................................7
Global rotation degrees...............................................................................7
Global scale.................................................................................................8
Global transform.........................................................................................9
Z index......................................................................................................10
Z as relative...............................................................................................11
Methods:........................................................................................................12
Apply_scale...............................................................................................12
Get_angle_to.............................................................................................13
Get_relative_transform_to_parent............................................................13
Global_translate........................................................................................14
Look_at.....................................................................................................15
Move_local_x...........................................................................................15
Move_local_y...........................................................................................16
Rotate........................................................................................................17
To_global..................................................................................................18
To_local.....................................................................................................18
Translate....................................................................................................18
GD Script in programming.................................................................................19
While loop.....................................................................................................19
For loop..........................................................................................................22
If else.............................................................................................................24
Match.............................................................................................................26
Function.........................................................................................................28
Array..............................................................................................................30
Dictionary......................................................................................................34
Class @GDScript...............................................................................................37
Methods.........................................................................................................37
Color8.......................................................................................................39
ColorN.......................................................................................................40
Abs............................................................................................................41
Acos..........................................................................................................41
Asin...........................................................................................................42
Assert........................................................................................................42
Atan...........................................................................................................42
Atan2.........................................................................................................42
Bytes2var..................................................................................................43
Cartesian2polar.........................................................................................43
Ceil............................................................................................................44
Char...........................................................................................................45
Clamp........................................................................................................46
Convert......................................................................................................46
Cos............................................................................................................46
Cosh..........................................................................................................47
Db2linear...................................................................................................47
Decimals...................................................................................................48
Dectime.....................................................................................................48
Deg2Rad...................................................................................................48
Dict2inst....................................................................................................49
Ease...........................................................................................................49
Exp............................................................................................................50
Floor..........................................................................................................50
Fmod.........................................................................................................50
Fposmod....................................................................................................51
Funcref......................................................................................................51
Get_stack...................................................................................................52
Hash..........................................................................................................52
Inst2dict.....................................................................................................53
Instance_from_id......................................................................................53
Inverse_lerp...............................................................................................53
Is_inf.........................................................................................................54
Is_instance_valid.......................................................................................54
Is_nan........................................................................................................54
Len............................................................................................................55
Lerp...........................................................................................................55
Linear2db..................................................................................................56
Load..........................................................................................................56
Log............................................................................................................56
Max...........................................................................................................57
Min............................................................................................................58
Nearest_po2..............................................................................................58
Parse json..................................................................................................58
Polar to cartesian.......................................................................................59
Pow...........................................................................................................59
Preload......................................................................................................59
Print...........................................................................................................60
Print debug................................................................................................60
Class Static Body 2D..........................................................................................62
Properties:......................................................................................................62
Constant linear velocity............................................................................62
Mastering Godot 1

New project creation


After opening a game engine for the first time click cancel in the

dialog box and click once on the new project button in a second

dialog, you need to enter a name for your project and to create

the project in a new blank folder. After that, you can select open

GL 3.0 or 2.0 (web project) and click the create and edit button.

Create 2D scene
Now we will create the 2D scene, so click on the "2D scene"

button. This will create a 2D node.

GD Script
You can add Godot script attaching it to a node. Click to micro

button scroll-like with the green plus sign to add it. You can press

the right button and select the attach script also. GD Script is a

default script language for coding in Godot. Use a template with a

simple code part (default) in the beginning, and later you can

select a blank or script without comments. Click "create" in attach

node script dialog window.


Mastering Godot 2

Class 2D Node
This is a fundamental class for other 2D nodes. Class is inherited

from the node class and has a position, rotation, scale, and z-

index properties.

Properties:
position
rotation
rotation_degrees
scale
transform
global_position
global_rotation
global_rotation_degrees
global_scale
global_transform
z_index
z_as_relative

Position
Position can be set and can be retrieved from 2D object. For

position setting use set_position(), and to retrieve position use

get_position(). Vector2 variable need to be defined for

set_position() method. When you use variable with get_position()

method, variable will be vector2.


Mastering Godot 3

Example:
extends Node2D

func _ready():
var pos = Vector2(21,21)
self.set_position(pos)

Example comment:
For example, "self" represents an extended node – Node 2D. "Var"

is used to define variable. Vector2 is a variable type for 2D space

with horizontal and vertical space defined. The first variable in

vector2 is horizontal, and second variable is vertical. "Func"

represents function – part of code. Function ready() automatically

starts when you start a game scene and you don’t need to call it.

Rotation
Rotation can be set and can be retrieved from 2D object. For

rotation setting use set_rotation(), and to retrieve rotation use

get_rotation(). Rotation is set in radians. When you retrieve

rotation, variable will be in radians. To convert radians to degrees,

the key is knowing that 180 degrees is equal to pi radians. Then

multiply the measurement in radians by 180 divided by pi. For direct

work in degrees see rotation degrees property. In calculation, one

radian is 57.2958.
Mastering Godot 4

Example:
# example code can be part of ready function
var rot = 1
self.set_rotation(rot)
var rot_deg = rot * 180 / PI

Example comment:
In this example you can see symbol “#”. This symbol is used for

one line comment. The example also includes symbols for

mathematical operations (* for multiplication and / for division) as

well as a symbol for pi constant. Constant that represents how

many times the diameter of a circle fits around its perimeter. It is

approximately equal to 3.14159.

Scale
To scale in 2D space, the "scale" is used. The set_scale () method is

used for set, and the get_scale () method is used to get scale value.

For the following example to work, move the default Godot sprite into

2D scene space. This way the sprite node will be the child node for the

2D node.

Example:
extends Node2D

export var sca = Vector2(0,0)

func _ready():
sca = Vector2(3,3)
self.set_scale(sca)
print(self.get_scale())
Mastering Godot 5

Example comment:
Export var is used when we want to enable the value of a particular

variable to be changed. It can be used when testing code and

initially defining values. The print command prints a value in the

“output” window.

Transform
Transform allows you to define position and rotation in 2D space.

This property uses the transform2D variable defined by two

parameters. Rotation(in radians) and position in 2D space. Use

set_transform() method to set transform, and get_transform() to

retrieve transform.

Example:
extends Node2D

func _ready():
transform_object(1,Vector2(60,60))

func transform_object(rot,pos):
var trans = Transform2D(rot,pos)
self.set_transform(trans)
var for_print = self.get_transform()
print("Transform2D: " + str(for_print))
Mastering Godot 6

Example comment:
In the example we have user defined function. This function is

called from ready with function name. User function have two

parameters. These parameters are later used in transform2D.

When you want to print some text via the "print" command, the

text should be in quotation marks. Use the "+" character to

connect parts of the text. Use the str () command to translate

numeric values into text.

Global position
Position in scene can be set and can be retrieved from 2D object.

For position setting use set_global_position(), and to retrieve

position use get_global_position(). Vector2 variable need to be

defined for set_global_position() method. When you use variable

with get_global_position() method, variable will be vector2.

Example:
extends Node2D

const global_pos = Vector2(18,18)

func _ready():
self.set_global_position(global_pos)
var get_pos = self.get_global_position()
print(get_pos)
Mastering Godot 7

Example comment:
"Const" is used when you declare a constant variable.

Global rotation
Global rotation can be set and can be retrieved from 2D object. For

rotation setting use set_global_rotation(), and to retrieve rotation

use get_global_rotation(). Rotation is set in radians. When you

retrieve rotation, variable will be in radians.

Example:
var get_rot = self.get_global_rotation()
print(get_rot)
""" Global rotation use radians and
global rotation degrees use degrees """

Global rotation degrees


Global rotation can be set and can be retrieved from 2D object in

degrees. For rotation setting use set_global_rotation_degrees(),

and to retrieve rotation use get_global_rotation_degrees().

Rotation is set in degrees. When you retrieve rotation, variable

will be in degrees.

Example:
var get_rot = self.get_global_rotation_degrees()
if get_rot > 45:
print(“Object rotation is larger than 45.degrees”)
Mastering Godot 8

Example comment:
The example uses conditional branching. Only if the value is

greater than 45 does a printout appear in the output window.

Global scale
To scale in scene 2D space, the "scale" is used. The

set_global_scale () method is used for set, and the

get_global_scale () method is used to get scale value.

Example:
func _ready():
global_scale()

func global_scale():
var get_sca = self.get_global_scale()
var default = Vector2(1,1)
if get_sca == default:
print("Global scale is default")
else:
print("Global scale is user defined.")

Example comment:
In conditional branch “else” command is used. If variables are not

equal (symbol “==”)then the text from another print command will

be in the "output" window.


Mastering Godot 9

Global transform
Global transform allows you to define position and rotation in 2D

space. This property uses the transform2D variable defined by two

parameters. Rotation(in radians) and position in 2D space. Use

set_global_transform() method to set transform, and

get_global_transform() to retrieve transform. Transform 2D can

be defined with three vector values. The first value is the x-axis,

the second value is the y-axis, and the third value is the

translation offset.

Example:
extends Node2D

func _ready():
var set_tra = Transform2D(Vector2(1,0),Vector2(0,1),Vector2(0,0))
global_transform()

set_tra = Transform2D(1,Vector2(9,9))
self.set_global_transform(set_tra)
global_transform_2()

func global_transform():
var get_tra = self.get_global_transform()
print(get_tra)

func global_transform_2():
var get_tra = self.get_global_transform()
print(str(get_tra) + str(self.get_global_rotation()))
Mastering Godot 10

Example comment:
In the example, we have two user functions. The first function has

a 2D transform defined by three vector values. The second

function has a 2D transform defined with two values, rotation, and

position.

Z index
Z index or rendering order determines in which layer a particular

object will be displayed. To set z index use the set_z_index()

method. Use the get_z_index() method to get z index values. The

default value is 0, higher values show objects above, and lower

values show objects below default values.

Example:
extends Node2D

func _ready():
var get_zin = self.get_z_index()
match get_zin:
0:
print("Default value.")
1:
print("This object is above")
-1:
print("This object is below")
Mastering Godot 11

Example comment:
In this example, a conditional branch – the "match" is used. When

you use this conditional branching, you first define the variable

(eg get_zin) and then the options. If the option is fulfilled then

you can enter a specific code (eg print).

Z as relative
Z as relative or rendering order determines in which layer a

particular object will be displayed. To set “z as relative” use the

set_z_as_relative() method. Use the is_z_relative() method to get

z index value. The value for "z as relative" is boolean. This value

can be true or false. If true, the node's Z-index is relative to its

parent's Z-index.

Example:
extends Node2D

func _ready():
var get_zin = $icon.is_z_relative()
match get_zin:
true:
print("Z is relative")
false:
print("Z as relative is off")
Mastering Godot 12

Example comment:
In the example, the "$" character is used. This character allows

you to access any node that belongs to the 2D node. The icon is a

child node added when you drag-drop sprite image into the scene.

Methods:
apply_scale()
get_angle_to()
get_relative_transform_to_parent()
look_at()
move_local_x()
move_local_y()
rotate()
to_global()
to_local()
translate()

Apply_scale
Apply scale is a method to multiply the size of the visible 2D game

objects. To set you to need to use the vetor2 variable. There are

two parameters of vector2, horizontal scale multiplication, and

vertical scale multiplication.

Example:
extends Node2D

func _ready():
.apply_scale(Vector2(3,3))
Mastering Godot 13

Example comment:
When you use symbol “.” it’s same effect as you use self.

Get_angle_to
When you use the “get_angle_to” method, you will get the result

in radians. This will be an angle toward the 2D point. Point is

defined with Vector2 variable.

Example:
extends Node2D

func _ready():
var angle = .get_angle_to(Vector2(90,3))
angle = str(angle * 180/PI)
print("Angle toward the point in degrees are: " + angle)

Get_relative_transform_to_parent
This method returns the tranform2D value. The tranform2D value

is relative. Transform2D is defined with three vector2 values. The

first value is the rotation segment on the x-axis, the second value

is the rotation segment on the y-axis, and the third value is

relative position of the node(translation offset). For the current

example, you need to add a label node. Using the Godot IDE, first,

click on the "+" sign (Control + A) on the left. Then, type "label" in

the search field and click on the "create" button.


Mastering Godot 14

Example:
extends Node2D

func _ready():
var rel_tra = $icon.get_relative_transform_to_parent(self)
var label_txt = str(rel_tra.get_rotation() * 180 / PI)
$Label.text = "Rotation is: " + label_txt

Example comment:
In the example, a node label with the "text" property is used. A

label allows text to be displayed on the screen. You can use the

character "W" to move within 2D space. Use the "Q" key to return

to select mode.

Global_translate
This method adds the value of vector2 to the position of the

object in 2D space.

Example:
extends Node2D

onready var n = 0

func _ready():
self.set_position(Vector2(12,30))

func _process(delta):
if n < 90:
self.global_translate(Vector2(1,0))
n += 1
Mastering Godot 15

Look_at
The method allows the 2D node to rotate to the point specified by

the vector2.

Example:
extends Node2D

onready var n = 0

func _ready():
self.set_position(Vector2(12,30))
$icon.set_rotation_degrees(-155.5)

func _process(delta):
if n < 300:
self.global_translate(Vector2(1,0))
self.look_at(Vector2(120,120))
n += 1

Move_local_x
The method moves an object on the x-axis. The method need to

be inside the process function. The speed of translation is defined

as a float var. If scaled is false, normalizes the movement.

Example:
func _ready():
self.set_position(Vector2(12,30))
“”” Two empty lines between function are
good style for coding.“””

func _process(delta):
if self.get_position().x < 90:
self.move_local_x(0.6,false)
Mastering Godot 16

Move_local_y
Applies a local translation on the node's Y axis based on the Nodes

process()'s delta. If scaled is false, normalizes the movement.

Example:
onready var change = false

func _ready():
self.set_position(Vector2(33,30))

func _process(_delta):
# Towards down
if self.get_position().y < 81 and change == false:
self.move_local_y(0.9,false)
elif self.get_position().y > 81.3:
change = true

# Movement towards up
if self.get_position().y > 30 and change:
self.move_local_y(-0.9,false)
print(self.get_position().y)
elif self.get_position().y < 30:
change = false

Example comment:
"Else if" in conditional branching means that the code line is

executed only if the previous condition is not met. A good way to

write code is to leave one blank line between the key elements

within the function. If you do not intend to use delta time and do

not want to see an error warning, type an underscore in front of

the word delta.


Mastering Godot 17

Rotate
The “rotate” method allows the node to be rotated in 2D space.

The value for rotation is in radians. For this example, you will need

to add a node “timer”. Using the Godot IDE, first, click on the "+"

sign (Control + A) on the left. Then, type "timer" in the search

field and click on the "create" button. In the "inspector" window,

set wait time to 3.sec and check to autostart box. In the connect

signal window, click the connect button. Node 2D should be

selected. This will give you a feature that will be repeated every 3

seconds.

Example:
func _ready():
self.set_position(Vector2(33,30))

func _process(_delta):
pass

func _on_Timer_timeout():
self.rotate(90 * 0.0174533)

Example comment:
When you do not use the function currently and plan to use it,

type "pass" in the first line of code.


Mastering Godot 18

To_global
The method "to_global" converts local coordinate to global

coordinate. The example also uses the “translate” method for

object movement in 2D space.

Example:
extends Node2D

func _process(delta):
if $icon.get_position().x < 30:
$icon.translate(Vector2(0.3,0.3))
var local_pos = "Local position: " + str($icon.get_position())
var global_pos = " Global position: " + str($icon.to_global($icon.get_position()))
$Label.text = local_pos + global_pos

To_local
The method "to_local" converts global coordinate to local

coordinate.

Translate
The “translate” method translates the node by the given offset in

local coordinates. See "to_global" method example.


Mastering Godot 19

GD Script in programming
In the next part of the book, you will learn how to program

through real-life examples. Every example has a possible

implementation. We will start with simple examples, but examples

will become more complex over time. This book chapter is useful

for the beginners.

While loop
"While" is a loop that repeats as long as the condition is fulfilled.

while condition

some code

Let's look at an example of "while loop".

Example:
onready var a = [0,1,3,2,5,7,3,4,5,0,5,6,7,2]

func _ready():
while typeof(a[n]) == TYPE_INT :
print(a[n])
n += 1
In this example, code prints the contents of a string if the content

type is numeric. The “typeof” method is used to check the type of

content. You can use the “typeof” method to filter large groups of

data.
Mastering Godot 20

Possible type labels for this method are:

TYPE_NIL = 0 Variable is of type nil (only applied for


null).
TYPE_BOOL = 1 Variable is of type bool.
TYPE_INT = 2 Variable is of type int.
TYPE_REAL = 3 Variable is of type float/real.
TYPE_STRING = 4 Variable is of type String.
TYPE_VECTOR2 = 5 Variable is of type Vector2.
TYPE_RECT2 = 6 Variable is of type Rect2.
TYPE_VECTOR3 = 7 Variable is of type Vector3.
TYPE_TRANSFORM2D = 8Variable is of type Transform2D.
TYPE_PLANE = 9 Variable is of type Plane.
TYPE_QUAT = 10 Variable is of type Quat.
TYPE_AABB = 11 Variable is of type AABB.
TYPE_BASIS = 12 Variable is of type Basis.
TYPE_TRANSFORM = 13Variable is of type Transform.
TYPE_COLOR = 14 Variable is of type Color.
TYPE_NODE_PATH = 15 Variable is of type NodePath.
TYPE_RID = 16 Variable is of type RID.
TYPE_OBJECT = 17 Variable is of type Object.
TYPE_DICTIONARY = 18 Variable is of type Dictionary.
TYPE_ARRAY = 19 Variable is of type Array.
TYPE_RAW_ARRAY = 20 Variable is of type PoolByteArray.
TYPE_INT_ARRAY = 21 Variable is of type PoolIntArray.
TYPE_REAL_ARRAY = 22 Variable is of type PoolRealArray.
TYPE_STRING_ARRAY = 23 Variable is of type PoolStringArray.
TYPE_VECTOR2_ARRAY = 24 Variable is of type PoolVector2Array.
TYPE_VECTOR3_ARRAY = 25 Variable is of type PoolVector3Array.
TYPE_COLOR_ARRAY = 26 Variable is of type PoolColorArray.
TYPE_MAX = 27 Marker for end of type constants.
Mastering Godot 21

The following example prints only numeric values if they are non-

zero. This means that numbers from a one-dimensional array will

be printed up to zero.

while typeof(a[n]) == TYPE_INT && a[n] != 0:


print(a[n])
n += 1
How would you check if the data type is vector? You would type

vector2 or vector3. See example.

while typeof(a[n]) == TYPE_VECTOR2:


# or while typeof(a[n]) == 5:
With the "break" command you can stop executing the while loop.

In the example, you can see how the conditional branching (if) is

used together with the “while” loop.

Example:
func code_test():
var a = 0
while a < 7:
print(a)
a += 1
if a == 5:
print("Make a break at 5")
break
Note: Python allows the “else” command to be used in the while

loop.

Use the CONTINUE command to stop current iteration and continue

with next.
Mastering Godot 22

Example:
func code_test():
var a = 0
while a < 7:
a += 1
if a == 5:
print("Continue after 5")
continue
print(a)
For loop
"For loop" repeats within the defined range from to. When using

an array or dictionary, use their name as in the example.

onready var a = [0,1,3,2,5,7,3,4,5,0,5,6,7,2] # Array

for i in a:
print(a[i]) # Prints array elements
The following example shows how to add up all the numerical

elements of a single array. The example uses a “range” function.

The "len" command is used to get the number of elements in an

array or in a string.

var sum = 0
for i in range( 1,len(a) ):
sum += a[i]
Rank can have a defined step, in the example, every third element

in the rank is printed.

func code_test():
var i = 0
for i in range(0,30,3):
print(i)
Mastering Godot 23

Only numbers that we want to use can be defined in a rank. For

example, to print only certain elements of a string.

func code_test():
var i = 0
for i in [6,12,3,9]:
print(a[i])
In addition, you can type in the string name and use its elements

(letters) through the "for" loop.

func code_test():
var hello = "Hello GD"
for i in hello:
print(i)
Use the CONTINUE command to stop current iteration and continue

with next.

func code_test():
var hello = "Hello GD"
for i in hello:
if i==" ":
continue
print(i)
Mastering Godot 24

If else
Conditional branching using the IF command is an old programming

technique. In addition to this command, ELIF and ELSE commands

are also used. Let's look at examples.

if typeof(a[n]) == TYPE_STRING && a[n]=="":


n += 1
The example uses comparison operators, such as the "=="

character, let's look at what other comparison operators can be

used.

== equals
> greater than
< less than
>= greater or equal
<= less or equal
!= not equals
The logic operator “&&” is also used in the example, let's look at

what other logical operators can be used.

&& AND boolean and


|| OR boolean or
! NOT boolean not
Now, let's explain current example. Conditional branching checks

the data type from a one-dimensional string is a string. It also

checks that the string is content-free.


Mastering Godot 25

If the conditions are met, the counter is increased by one. The

following example shows the use of an ELIF command.

func code_test():
var hi = "Hi GD"
var ln = len(hi)
if ln >=5:
print("Five or more letters")
elif ln <=4:
print("Four or less letters")
See also an example for using the ELSE command.

func code_test():
var hi = "Hi GD Script"
var ln = len(hi)
if ln < 6:
print("Less than six letters")
else:
print("Six or more letters")
IF and ELSE can be used in conditional expressions, let us see an

example.

var is_nice = true


var state = "nice" if is_nice else "not nice"
print(state)
Mastering Godot 26

Match
Using the match command we have the possibility of conditional

branching. This type of conditional branching is specific and there

are different ways to use it. Example shows use with numeric

values.

onready var a = [0,1,3,2,5,7,3,4,5,0,5,6,7,2]


onread var modes = [0,0,0,0,0,0,0,0]

func ready():
for i in a:
match a[i]:
1:
modes[1] += 1
2:
modes[2] += 1
3:
modes[3] += 1
4:
modes[4] += 1
5:
modes[5] += 1
6:
modes[6] += 1
7:
modes[7] += 1
print("Modes are: " + str(modes))
The program code in the example calculates the mod value for the

elements of a one-dimensional array.

If you have the same code for your different MATCH options you

can set it up like this.


Mastering Godot 27

Example:
for i in a:
match a[i]:
1,2,2:
print("Variable 1,2 or 3 found")
The following example will show you how to use a MATCH for

counting different types of data in an array.

func code_test():
var data = ["text",33,42,6,"e"]
var string = 0
var ints = 0
for i in range(0,len(data)):
match typeof(data[i]):
TYPE_STRING:
string += 1
TYPE_INT:
ints += 1
print("Strings: " + str(string))
print("Integers: " + str(ints))
Mastering Godot 28

Function
In the following examples we will see how the FUNCTION is used.

Let's first see how to declare a function with a single parameter.

This function will sum all the numeric values in the array.

func calc_sum(sum):
var summ = 0
for i in sum:
summ += sum[i]
print(summ)
The function is called via the function name, the parameters for

the function are defined in parentheses.

onready var a = [0,1,3,2,5,7,3,4,5,0,5,6,7,2]

func _ready():
calc_sum(a)
The function may contain code without parameters. This can be

used when we repeatedly need to perform a specific activity.

func calc_sum() → void: # void when return isn’t used


var summ = 0
for i in a:
summ += a[i]
print(summ)
The function can return a value, then the RETURN command is

used. See an example.

func _ready():
var sum = calc_sum()
print("Array elements sum is: " + str(sum))
Mastering Godot 29

func calc_sum():
var summ = 0
for i in a:
summ += a[i]
return summ
In the following example, you will see the sum of two numbers,

the function returns a numeric INT value.

func _ready():
var sum = calc_sum(21,45)
print("Sum is: " + str(sum))

func calc_sum(a,b) ->int :


return a + b
Let's look at other types of data to restore function values.

void when function didn’t return value


String function return string value
Array array value
Dictionary dictionary data type value
Mastering Godot 30

Array
A matrix or array can contain different data groups. Let's look at

how to create a one-dimensional matrix.

onready var arr = [] # Create all types array


onready var arr = Array() # create all types array
onready var arr = PoolIntArray() # integer array
Let's see what other types of data can be stored by specially

designed arrays.

PoolByteArray integers from 0 to 255


PoolColorArray color
PoolRealArray float
PoolStringArray string
PoolVector2Array vector2 for 2D space
PoolVector3Array vector3 for 3D space
Using the append method, an element can be added to the array.

If the string is empty a new element will be added to the zero

position. If there are elements in the array, a new one will be

added after the last one.

arr.append(6)
Example:
onready var arr = PoolIntArray()

func _ready():
arr.append(6)
print(arr)
You can define default values in an array individually or for

multiple elements at once.


Mastering Godot 31

func _ready():
for i in range(0,15):#multiple elements with for loop
arr.append(0)
Array elements can be defined when declaring the array itself.

onready var arr = [39,51,36]


The COUNT command lets you count the number of the same

number elements in a row. The example uses RANDOMIZE and RANDI

to generate random numbers.

func _ready():
randomize()
for i in range(0,101):
var rnd = randi() % 100
arr.append(rnd)
print(arr.count(36))
The SORT command is used to sort the numeric or string

(alphabetical) data.

onready var arr = [39,51,36]

func _ready():
randomize()
for i in range(0,101):
var rnd = randi() % 100
arr.append(rnd)
arr.sort()
print(arr)
You can use the FIND command to find a specific value within an

array.
Mastering Godot 32

func _ready():
randomize()
for i in range(0,101):
var rnd = randi() % 100
arr.append(rnd)
var rnd = randi() % 100
print(arr)
if arr.find(rnd):
print("Number " + str(rnd) + " is found
in an array!")
There are many other commands for working with an array. See

comments and examples.

onready var arr = [39,51,36]

func _ready():
randomize()
arr.insert(1,93) # insert element into array
print(arr[1]) # print element at position
arr[2] = 33 # declare value of element
print(arr)
arr.shuffle() # randomly change elements in array
print(arr)
An array can also be defined with different types of elements.

onready var arr = [39,51,36,"some text","&",15]


Such arrays can be filtered into arrays containing only one data

type.
Mastering Godot 33

Example:
onready var arr = [39,51,36,"some text","&",15]

func _ready():
var int_arr = []
var str_arr = []
for i in range(0,len(arr)):
if typeof(arr[i]) == TYPE_INT:
int_arr.append(arr[i])
if typeof(arr[i]) == TYPE_STRING:
str_arr.append(arr[i])
print(int_arr)
print(str_arr)

Note:
When working with larger groups of data, it is a good idea that the

data belong to the same type.


Mastering Godot 34

Dictionary
Dictionary allows you to store different types of data. Each data

or data group is stored under a specific key. When declaring, the

key is entered first, then the colon, followed by the value.

onready var dict = {1: 9, 2: 24, 3: 9}


Let's look at an example that prints the contents of a dictionary.

onready var dict = {1: 9, 2: 24, 3: 9}


func _ready():
print(dict)
The following example lists the size, keys, and values of a

dictionary.

onready var dict = {1: 9, 2: 24, 3: 9}

func _ready():
print(dict.size()) # how many elements are in
print(dict.keys()) # list of keys
print(dict.values()) # list of values
You can change the key-value if the key exists, or you can add a

new key and value after the last entry.

func _ready():
dict[1] = 6 dict["new_key"] = "Text value"
print(dict)
One dimensional matrix can be part of the dictionary. Let's see an

example of it.

onready var dict = {1: 9, 2: 24, 3: [9,18,24,30]}


func _ready():
print(dict[3]) # print values of key
print(dict[3][2]) # print element of array under key
Mastering Godot 35

See how you can create default values for a DICTIONARY .

onready var dict = {}

func _ready():
for i in range(0,9):
dict[i] = 0
Creating a numeric array within the dictionary.

onready var dict = {}

func _ready():
for i in range(0,9):
dict[i] = 0
dict[3] = [3,9,15,18,21]
print(dict)
Creating a string array within a dictionary.

onready var dict = {}

func _ready():
for i in range(0,9):
dict[i] = 0
dict[4] = ["alfa","beta","delta"]
print(dict)
In the following example, you will see how to create a dictionary in

the dictionary.

onready var dict = {}

func _ready():
for i in range(0,9):
dict[i] = 0
dict[5] = {"first":"very good","second": "good", "third":
"acceptable"}
print(dict)
Mastering Godot 36

The following example shows how to access values within an ARRAY

or DICTIONARY that are part of a unique DICTIONARY .

Example:
onready var dict = {}

func _ready():
for i in range(0,9):
dict[i] = 0
dict[3] = [3,9,15,18,21]
dict[4] = ["alfa","beta","delta"]
dict[5] = {"first":"very good","second":"good","third":"acceptable"}
print(dict[3][3])
print(dict[4][0])
print(dict[5]["first"])
Mastering Godot 37

Class @GDScript
@GDScript is one of the core classes with built-in features for GD

Script.

Methods
Color8(r8,g8,b8,a8)
ColorN(name, alpha = 1.0)
abs(s)
cos(s)
asin(s)
assert(condition)
atan(s)
atan2(y,x)
bytes2var(bytes, allow_objects = false)
cartesian2polar(x,y)
ceil(s)
char(ascii)
clamp(value, min, max)
convert(what, type)
cos(s)
cosh(s)
db2linear(db)
decimals(step)
dectime(value, amount, step)
deg2rad(deg)
dict2inst(dict)
ease(s, curve)
exp(s )
floor(s )
fmod(x, y )
fposmod(x, y )
funcref(instance, funcname )
Mastering Godot 38

get_stack()
hash(var )
inst2dict(inst )
instance_from_id(instance_id )
inverse_lerp(from, to, weight )
is_inf(s)
is_instance_valid(instance )
is_nan(s )
len(var )
lerp(from, to, weight )
linear2db(nrg)
load(path)
log(s)
max(a, b)
min(a, b)
intnearest_po2(value)
parse_json(json)
polar2cartesian(r, th)
pow(x, y)
preload(path)
print( ... )
print_debug( ... )
print_stack()
printerr( ... )
printraw( ... )
prints( ... )
printt( ... )
push_error(message)
push_warning(message)
rad2deg(rad)
rand_range(from, to)
rand_seed(seed)
randf()
randi()
Mastering Godot 39

randomize()
range( ... )
range_lerp(value, istart, istop, ostart, ostop)
round(s)
seed(seed)
sign(s)
sin(s)
sinh(s)
smoothstep(from, to, weight)
sqrt(s)
stepify(s, step)
str( ... )
str2var(string)
tan(s)
tanh(s)
to_json(var)
type_exists(type)
typeof(what)
validate_json(json)
var2bytes(var, full_objects = false)
var2str(var)
WeakRefweakref(obj)
wrapf(value, min, max)
wrapi(value, min, max)
yield(object = null, signal="")

Color8
Method color8 returns a 32 bit color with red (r8), green(g8),

blue(b8) and alpha(a8) channels. Each channel has 8 bits of

information ranging from 0 to 255. The nodes needed for this

example are sprite, label, and timer (autostart, wait_time 0.03).


Mastering Godot 40

Example:
extends Node2D

onready var i = 1

func _ready():
.set_position(Vector2(30,30))
var col = Color8(120,30,120,255)
$icon.set_modulate(col)

func _on_Timer_timeout():
if i < 256:
var col = Color8(i,30,120,255)
$icon.set_modulate(col)
i += 1
else:
$Timer.stop()
$Label.text = "Timer stops!"

ColorN
Method ColorN returns a color according to the standardized name

with alpha ranging from 0 to 1. A list of supported color names can

be found in the game engine help section or in the Godot

documentation. For the proper functioning of the example, one

“label” node must be added.

Example:
func _ready():
.set_position(Vector2(30,30))
var col = ColorN("dodgerblue",1)
$Label.set_modulate(col)
$Label.set_scale(Vector2(3,3))
$Label.text = "Dodgerblue color"
Mastering Godot 41

Abs
Method abs returns the absolute value of parameter.

Example:
func _ready():
var numb = - 0.3
numb = abs(numb)

Acos
Method acos returns the arc cosine of parameter in radians. In the

example, the value in radians is converted to degrees using the

rad2deg method.

Example:
func _ready():
var numb = - 0.3
numb = abs(numb)
var a_cos = acos(numb)
var a_sin = asin(numb)
var a_cos_text = "Arc sin angle is: " + str(rad2deg(a_cos))
var a_sin_text = " Arc cos angle is: " + str(rad2deg(a_sin))
$Label.text = a_cos_text + a_sin_text

Example Comment:
Cosine is a trigonometric mathematical function. Cosine is the

value of the angle, and the arc of the cosine is the angle of value.

Otherwise, trigonometry literally means measuring a triangle.

Think of a right triangle. To visually understand relationships, see

the picture.
Mastering Godot 42

Asin
Method asin returns the arc sine of parameter in radians. Use to

get the angle of sine s. Look at the example for acos.

Assert
The assert method can be used as a debugging tool. The program

resumes after assertion only if the condition is true. If the

condition is not fulfilled, the program is terminated.

Example:
export var l = 0

func _ready():
assert(l > 0 and l < 12)
$Label.text = "App cont"

Atan
Method atan returns the arc tangent of parameter in radians. Use

to get the angle of tan s.

Atan2
Method atan2 returns the arc tangent from y,x position.
Mastering Godot 43

Example:
var a = 0

func _ready():
a = atan2(1,1)
$Label.text = "Atan is: " + str(rad2deg(a))

Bytes2var
Method bytes2var decodes a byte array back to a value. When

allow_objects are true decoding is allowed. Condition "len < 4 * 9"

should be met for a byte array.

Example:
func _ready():
var array = PoolByteArray()
for f in range(0,42):
array.append(int(12))
$Label.text = "Array size: " + str(array.size())
for byte in array:
print(byte)
print( bytes2var(array,true) )
#warning-ignore-all:unused_variable

Example comment:

The example uses an array that is designed to store bytes. The

"append" method is used to add an element to an array, and the

"int" method to translate value into an integer value.

Cartesian2polar
This method converts a 2D position from a Cartesian coordinate

system to a polar coordinate system.


Mastering Godot 44

Example:
extends Node2D

onready var pos_1 = Vector2(0,0)


onready var pos_2 = Vector2(100,100)

func _ready():
pos_1 = cartesian2polar(pos_1.x,pos_1.y)
pos_2 = cartesian2polar(pos_2.x,pos_2.y)
$Label.text = "Initial polar position: " + str(pos_1)
$Label.text += " Final polar position: " + str(pos_2)
#warning-ignore-all:unused_variable

func _draw():
var posp_1 = polar2cartesian(pos_1.x,pos_1.y)
var posp_2 = polar2cartesian(pos_2.x,pos_2.y)
draw_line(posp_1, posp_2 , Color.aliceblue, 0.3)

Example comment:
For this example, you need to have a label node added. The

Cartesian coordinate system is defined by the horizontal (x) and

vertical (y) positions. The polar coordinate system is determined

by the distance and angle from the base (0,0) position. The draw

function allows on-screen drawing. With the draw_line method you

can draw a line. The line is defined by the starting and ending

position, color, and thickness.

Ceil
The ceil method rounds the numerical value to higher.
Mastering Godot 45

No matter what the decimal value of a number is, the number will

be rounded up to a higher integer value.

Example:
extends Node2D

onready var number

func _ready():
number = rand_range(0,9)
$Label.text = "Random number is: " + str(number)
#warning-ignore-all:unused_variable

func _on_Button_button_down():
$Label.text +=" and ceil of number is " + str( ceil(number))

Example comment:
For this example, you need to add a node label and a node button.

Button nude should have a "button-down" signal set up which will

create a function _on_Button_button_down(). The method

rand_range create a random number.

Char
Method char returns a character as a String of the given ASCII

code. For the example code to function properly, a node label must

be added.

Example:

onready var values = [0,87,69,76,67,79,77,69]


Mastering Godot 46

func _ready():
var characters = ""
for i in range(0,26):
characters += str(i+65) + ":" + str(char(65+i)) + " "
for n in range(1,8):
$Label.text += char(values[n])
print(characters)

Clamp
This method clamps value and returns a value not less than min

and not more than max.

Example:
func _ready():
var random_number = 0
randomize()
random_number = rand_range(0,99)
$Label.text += "Initial value: " + str(random_number)
random_number = clamp(random_number,57,99)
$Label.text += " Clamp value: " + str(random_number)

Convert
Method converts from a type to another.

Example:
func _ready():
var value = false
value = convert(value, TYPE_STRING)
$Label.text = value

Cos
Returns the cosine of angle in radians.
Mastering Godot 47

Example:
onready var value = 0

func _ready():
value = cos(1.2)
$Label.text = str(value)

func _draw():
draw_line(Vector2(0,0),Vector2(100,120),Color.aliceblue,0.3)
var angle_line = polar2cartesian(180,value)
draw_line(Vector2(0,0),angle_line,Color.aliceblue,0.3)

Cosh
Method cosh returns the hyperbolic cosine in radians.

Example:
onready var value = 0
func _ready():
value = cosh(1.2)
$Label.text = str(value)

Db2linear
Method db2linear converts from decibels to linear energy.

Example:
onready var value = 20

func _ready():
if value == 20:
$Label.text = "wisper – 20dB"
value = db2linear(value)
$Label.text += " Sound energy level: " + str(value)
Mastering Godot 48

Decimals
Method decimals returns the position of the first non-zero digit,

after the decimal point.

Example:
onready var value = 20.0234

func _ready():
value = decimals(value)
$Label.text = "Integer decimal at " + str(value) + ".position"

Dectime
The dectime method reduces the value of a number. The value is

reduced by the product of two variables (amount and step).

Example:
onready var value = 21

func _ready():
value = dectime(value, 3, 0.3)
$Label.text = str(value)

Deg2Rad
Method deg2rad returns degrees converted to radians.

Example:
onready var angle = 18

func _ready():
var value = deg2rad(angle)
$Label.text += str(angle) + ".degrees are "
$Label.text += str(value) + ".radians"
Mastering Godot 49

Dict2inst
Method dict2inst converts a previously converted instance to a

dictionary, back into an instance.

Example:
extends Node2D

class temp_inst:
var a = 0
var b = 0
func print_param():
print(a)

func _ready():
var instance = temp_inst.new()
var dict = inst2dict(instance)
print(dict)
var inst = dict2inst(dict)
print(inst)

Example comment:

Using the class command, you can create a user class. Each

created class can have variables and functions.

Ease
The function is used in animation to store different types of

curves with low overhead. It's not really meant to be used from

code so much.
Mastering Godot 50

Exp
Method exp returns the natural exponential function.

Example:
func _ready():
for i in range(1,9):
var value = str(exp(i))
value = value.left(6)
$Label.text += str(i) + ": " + value + " "

Floor
Method floor rounds value to the closest smaller integer.

Example style:
func _ready():
randomize()
for i in range(1,9):
var value = str(rand_range(1,9))
value = value.left(6)
var round_value = floor(int(value))
$Label.text += " " + value + " " + str(round_value)

Fmod
Method fmod returns the floating-point remainder.

Example:

func _ready():
var a = 9
var b = 6.63
var c = fmod(a,b)
$Label.text = str(c)
Mastering Godot 51

Fposmod
Method fposmod returns the floating-point remainder that wraps

equally in positive and negative.

Example:
func _ready():
var a = -9
var b = 6.63
while a < 0:
var c = fposmod(a,b)
$Label.text += " " + str(a) + " " + str(c)
a += 1

Funcref
The @GDScript "funcref" method returns a reference of a

particular function. You need to enter the function name as an

argument to the "funcref" command. By using this method, you

are referencing an object that you can later call and use. Note that

there is also a "funcref" class that has the call_func method.

Example:
func foo():
return("func test text")

func _ready():
var f = funcref(self, "foo")
print(f.call_func())
Mastering Godot 52

Get_stack

Using the get_stack method will give you information about call

stacks. It's good to know that the call stack keeps track of active

subroutines.

Example:
func foo():
test()

func _ready():
foo()

func test():
print(get_stack())

Hash
Method "hash" transforms an integer hash key into an integer

hash result.

Example:
func _ready():
var a = hash_int("a")
var b = hash_int("b")
if b > a:
print("b is after a")

func hash_int(v):
var hash_value = hash(v)
print(v + ": " + str(hash_value))
return hash(v)
Mastering Godot 53

Inst2dict
Method inst2dict returns the passed instance converted to a

dictionary data.

Example:
onready var a = 3
const b = 6
var c = "text"

func _ready():
var d = inst2dict(self)
print(d)
print(d.keys())
print(d.values())

Instance_from_id
Each node within the Godot system has its own numeric id. Using

the instance methods _from _id, you can access the properties of

a particular node. For this, you need to know the numeric id value

of the node. For example code you need to add a label node.

Example:
func _ready():
var inst_id = $Label.get_instance_id()
var instance = instance_from_id(inst_id)
instance.text = "It's Ok"

Inverse_lerp
Lerp does an interpolation that returns values between the "from"

and "to". Inverse_lerp has third value, weight, which returns how

close is that value to the first and second one.


Mastering Godot 54

Example:
var ilerp = inverse_lerp(3, 5, 4) # returns 0.5
print(ilerp)

Is_inf
A method returns a value of true if the variable is negative or

positive infinite. “Pow” function returns the base to the exponent


power.

Example:
func _ready():
var result = pow(30,210)
print(is_inf(result))

Is_instance_valid
Method is_instance_valid returns true if the node is a valid object

(e.g. has not been deleted from memory).

Example:
func _ready():
$Label.free() # delete object from memory
if is_instance_valid($Label):
$Label.text = "Test text"
else:
print("Node is deleted from memory")
print_tree() # Show nodes tree

Is_nan
Method returns true if value is a NaN (Not-A-Number). For
example, the square root of a negative number would return a NaN. For
this example, you need a label node.
Mastering Godot 55

Example:
func _ready():
var value = sqrt(-9)
if is_nan(value):
$Label.text = "Variable is not a number"
else:
$Label.text = "Variable is an number"

Len
Returns length of var. Length is the character count of String,

element count of Array, size of Dictionary, etc.

Example:
func _ready():
var a = 402
var b = "Some text"
var c = [9,81,15,21,3,36]
if typeof(a) != TYPE_INT:
print(len(a))
print(len(b)) ; print(len(c))

Lerp
Method “lerp” linearly interpolates between two values by a

normalized value.

Example:
func _ready():
var a = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
for i in a:
print( lerp(1,10,i))
print(lerp(Vector2(i,i),Vector2(10,10),0.1))
var rgb_color = lerp(Color.aliceblue,Color.green,10)
rgb_color = Color(rgb_color)
$Label.add_color_override("font_color",rgb_color)
$Label.text += "test"
Mastering Godot 56

Linear2db
Converts from linear energy to decibels (audio).

Example:
func _ready():
for e in range(1,10):
print(linear2db(e))

Load
Using the "load" method, you can load a resource from the Godot

file system. Note: Resource paths can be obtained by right clicking

on a resource in the Assets Panel and choosing "Copy Path". For

this example, you need to add a "sprite" node.

Example:
onready var icon_image = load("res://icon.png")

func _ready():
$Sprite.set_texture(icon_image)

Log
Natural logarithm. The amount of time needed to reach a certain

level of continuous growth. Note: This is not the same as the log

function on your calculator which is a base 10 logarithm.

Example:
func _ready():
$Label.text = "Natural logorithm (1-9) …"
for i in range(1,10):
$Label.text +=" " + str(i) + ": " + str( log(i) )
Mastering Godot 57

Example:
var n = 2
var time = 0.1

func _ready():
$Label.text = "Natural logorithm (1-9) ... "

func _on_Timer_timeout():
if n < 10:
$Label.text +="0"
time = log(n)
print(time)
n += 1
$Timer.set_wait_time(time)

Max
Method “max” returns the maximum of two values. In the second

example, you can see the sorting of numbers using the max.

Example:
max(1, 2) # returns 2
max(-3.99, -4) # returns -3.99
Example:
onready var a = [0,3,12,6,69,9,15]

func _ready():
sort_w_max()
sort_w_max()
for i in a:
print(i)
Mastering Godot 58

func sort_w_max():
for i in range(1,len(a)):
if i+1 < len(a):
var max_value = max(a[i],a[i+1])
if max_value > a[i+1]:
a[i] = a[i+1]
a[i+1] = max_value

Min
Method min returns the minimum of two values.

Example:
onready var a = 0
onready var b = 9
onready var c = 6

func _ready():
$Label.text = "Minimal value from 0,9 and 6 are: "
var value = min(a,b)
value = min(value,c)
$Label.text += str(value)

Nearest_po2
Method “nearest_po2” returns the nearest larger power of 2 for

integer value.

nearest_po2(3) # returns 4
nearest_po2(4) # returns 4
nearest_po2(5) # returns 8

Parse json
Method parse_json parse json text to a Variant
Mastering Godot 59

Example :
func _ready():
var p = parse_json('["a", "b", "c"]')
if typeof(p) == TYPE_ARRAY:
print(p) # prints [a, b, c]
else:
print("unexpected results")

Polar to cartesian
Method polar2cartesian converts a 2D point expressed in the polar

coordinate system to the cartesian coordinate system.

Example:
func _ready():
var origin = 9 # distance from origin
var angle = deg2rad(45) # angle
var cartesian = polar2cartesian(origin,angle)
print(cartesian)

Pow
Method pow returns the result of x raised to the power of y.

Example:
pow(2, 5) # returns 32

Preload
Method preload returns a resource from the filesystem.

Example:
extends Node2D

onready var icon_image = preload("res://icon.png")


Mastering Godot 60

func _ready():
var sprite = Sprite.new()
sprite.set_texture(icon_image)
sprite.set_position(Vector2(32,32))
.add_child(sprite)

Print
Method print converts arguments to strings and prints them in the

output window.

Example:
func _ready():
var number_data = 3
var string_data = "GDScript"
var array = [1,3,15,3,12,21,39]
print(number_data)
print(string_data)
print(array)

Print debug
Method print_debug prints to output window when used in debug

mode.

Print stack

This method prints a stack track at code location. A stack is a data


structure used to store a collection of objects.

Example:
func _ready():
print_stack()
Mastering Godot 61
Mastering Godot 62

Class Static Body 2D


Static body for 2D Physics, not intended to move, good for objects

in the environment, such as walls or platforms.

Properties:
constant linear velocity
constant angular velocity
friction
bounce
physics material override

Constant linear velocity


Method "constant linear velocity" for the body does not move the

body but affects colliding bodies. Add StaticBody2D node for this

example. Also, add collisionshape2D as child node. Set collision

shape as rectangle shape. Use RigidBody2D to test examples. Add

circular collision shape for a rigid body. Don't forget to enable

"visible collision shapes" (menu Debug).

Example:
func _ready():
$StaticBody2D.set_position(Vector2(0,300))
$StaticBody2D.set_constant_linear_velocity(Vector2(9,9))
$StaticBody2D/CollisionShape2D.shape.set_extents(Vector2(240,12))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy