Mastering GD Script Free Ver2
Mastering GD Script Free Ver2
You are reading the expanded free version of the book "Mastering
translation right. For example, for the first thousand copies sold,
The book uses the MTH method for learning and is written for
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"
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
simple code part (default) in the beginning, and later you can
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
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"
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
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
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
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
“output” window.
Transform
Transform allows you to define position and rotation in 2D space.
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
When you want to print some text via the "print" command, the
Global position
Position in scene can be set and can be retrieved from 2D object.
Example:
extends Node2D
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
Example:
var get_rot = self.get_global_rotation()
print(get_rot)
""" Global rotation use radians and
global rotation degrees use degrees """
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
Global scale
To scale in scene 2D space, the "scale" is used. The
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
Global transform
Global transform allows you to define position and rotation in 2D
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
position.
Z index
Z index or rendering order determines in which layer a particular
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
Z as relative
Z as relative or rendering order determines in which layer a
z index value. The value for "z as relative" is boolean. This value
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
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
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
first value is the rotation segment on the x-axis, the second value
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
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
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
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
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
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 "+"
set wait time to 3.sec and check to autostart box. In the connect
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,
To_global
The method "to_global" converts local coordinate to global
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
GD Script in programming
In the next part of the book, you will learn how to program
will become more complex over time. This book chapter is useful
While loop
"While" is a loop that repeats as long as the condition is fulfilled.
while condition
some code
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
content. You can use the “typeof” method to filter large groups of
data.
Mastering Godot 20
The following example prints only numeric values if they are non-
be printed up to zero.
In the example, you can see how the conditional branching (if) is
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.
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
for i in a:
print(a[i]) # Prints array elements
The following example shows how to add up all the numerical
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
func code_test():
var i = 0
for i in range(0,30,3):
print(i)
Mastering Godot 23
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
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
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
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.
Match
Using the match command we have the possibility of conditional
are different ways to use it. Example shows use with numeric
values.
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
If you have the same code for your different MATCH options you
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
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.
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
func _ready():
calc_sum(a)
The function may contain code without parameters. This can be
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,
func _ready():
var sum = calc_sum(21,45)
print("Sum is: " + str(sum))
Array
A matrix or array can contain different data groups. Let's look at
designed arrays.
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
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.
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.
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
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.
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
Dictionary
Dictionary allows you to store different types of data. Each data
dictionary.
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
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.
func _ready():
for i in range(0,9):
dict[i] = 0
Creating a numeric array within the dictionary.
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.
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.
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
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),
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
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
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.
the picture.
Mastering Godot 42
Asin
Method asin returns the arc sine of parameter in radians. Use to
Assert
The assert method can be used as a debugging tool. The program
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
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
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:
Cartesian2polar
This method converts a 2D position from a Cartesian coordinate
Example:
extends Node2D
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
by the distance and angle from the base (0,0) position. The draw
can draw a line. The line is defined by the starting and ending
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
Example:
extends Node2D
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.
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:
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
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,
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
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
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
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
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
are referencing an object that you can later call and use. Note that
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
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
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
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,
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
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
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
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
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
Example:
func _ready():
print_stack()
Mastering Godot 61
Mastering Godot 62
Properties:
constant linear velocity
constant angular velocity
friction
bounce
physics material override
body but affects colliding bodies. Add StaticBody2D node for this
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))