GDScript 3.0.6 Cheat Sheet

[»] GDScript/Engine Overview

  • Godot is a 2D and 3D capable game engine, utilizing a unique node-tree structure for composing scenes.
  • Godot uses threads heavily for lifting and initializing data from the net or disk.
  • Godot embeds scripts in nodes and has a memory management model for resources.
  • Godot uses several built-in data types for 2D and 3D math.
  • GDScript is Godot's a high level, dynamically typed, Python-based programming language, utilizing OOP (Object-Oriented Programming) concepts such as single-inheritance.
  • Whitespace-sensitive syntax; Space or Tab characters are entered before line code to determine code scope or block, thus execution order. Technique called Offside-Rule.
  • "#" is a comment character. First use in any line of this character segments off any code to the right of this character, all characters in this segment being ignored by compiler and the application during runtime.
  • ALL TEXT is CASE SENSITIVE

[»] GDScript Preview

# TestNode (/w Script)
extends Node
 
# Member variables
const i_max = 10
export (bool) var do_count = false
 
# Functions
func _ready():
 if do_count == true:
  var i = 0
  while i < i_max:
   i+=1
   print(str(i))

[»] Built-In Types

Built-in types are stack-allocated. They are passed as values.
This means a copy is created on each assignment or when passing them as arguments to functions.
The only exceptions are Arrays and Dictionaries, which are passed by reference so they are shared.
(Not PoolArrays like PoolByteArray though, those are passed as values too)

Basic Built-In Types

  • null: contains no information and can not be assigned any other value.
  • bool: true or false value.
  • int: positive or negative integer number value.
  • float: floating point value (real numbers).
  • String: A sequence of characters in Unicode format. Can contain the standard C escape sequences. GDScript supports format strings.

Vector Built-In Types

  • Vector2: 2D vector type containing x and y fields. Can also be accessed as array.
  • Rect2: 2D Rectangle type containing two vectors fields: position and size. Alternatively contains an end field which is position+size.
  • Vector3: 3D vector type containing x, y and z fields. This can also be accessed as an array.
  • Transform2D: 3x2 matrix used for 2D transforms.
  • Plane: 3D Plane type in normalized form that contains a normal vector field and a d scalar distance.
  • Quat:
  • AABB:
  • Basis:
  • Transform:

Engine Built-In Types

  • Color:
  • NodePath:
  • RID:
  • Object:

Container Built-In Types

  • Array:
  • Dictionary:

[»] Data

  • Variables
  • Constants
  • Enums
  • Functions
  • Referencing Functions
  • Static Functions
  • Statements and Control Flow
  • if/else/elif
  • while
  • for
  • match

[»] Literals

  • 45
  • 0x8F51
  • 3.14
  • 58.1e-10
  • "Hello"
  • """Hello"""
  • @"Node/Label"

[»] Operators

  • x[index]
  • x.attribute
  • is
  • ~
  • -x
  • * / %
  • + -
  • « »
  • &
  • ^
  • |
  • < > == != >= <=
  • in
  • ! not
  • and &&
  • or ||
  • if x else
  • = += -= *= /= %= &= |=

[»] Identifiers

  • EX: i_max
  • Any string, limited to alphabetic characters (a to z and A to Z), digits (0 to 9) and _ is as an identifier.
  • Identifiers are case-sensitive (foo is different from FOO).
  • DO NOT BEGIN IDENTIFIERS WITH A DIGIT

[»] Keywords

  • Keywords are reserved words (tokens), operators (in, not, and, or), and built-in type names can’t be used as identifiers.
  • if/elif/else
  • for
  • do
  • while
  • match
  • switch
  • case
  • break
  • continue
  • pass
  • return
  • class
  • extends
  • is
  • self
  • tool
  • signal
  • func
  • static
  • const
  • enum
  • var
  • onready
  • export
  • setget
  • breakpoint
  • preload
  • yield
  • assert
  • remote
  • master
  • slave
  • sync
  • PI
  • TAU
  • INF
  • NAN

[»] Objects

  • Node.new()
  • Node.add_child(node_var)
  • load("res:Node_Location.tscn")
  • preload("res:GDScript_.gd")

[»] Vectors: Location and Rotation

  • X is left/right, (RED)
  • Y is up/down, (GREEN)
  • Z is forward/backward. (BLUE)

Node2D Properties

Location measured in pixels

Spatial Properties

Location measured in meters

[»] Useful Functions

file_exists( var)
get_tree().root
get_node( var)
load( var)
preload( var)
instance()
new()
add_child( var)
remove_child( var)
get_tree.get_nodes_in_group( var)
front()
back()
pop_front()
pop_back()
"if node is Spatial:"

node is a variable referring to a node instance

connect()
set_process( bool)
set_process_input( bool)
set_physics_process( bool)
func _ready()
func _process( delta)
func _input( event)
func _physics_process( delta)
yield( get_tree(), "idle_frame")
queue_free()
free()
weakref( var)
get_ref()
typeof( var)

================================================================================
[»] NOTES: WIP
================================================================================

if x.is_class(string type) == true: return

===============================================================
[»] VECTORS: LOCATION AND ROTATION
===============================================================
X is left/right, (RED)
Y is up/down, (GREEN)
Z is forward/backward. (BLUE)

Node2D Properties
> Location measured in pixels

> Position: Local 2D coordinates (x,y) of local position, relative to parent node.
> Rotation Degrees: Local 2D planar body's rotation (0-1440 degrees), relative to parent node.
> Scale: Transformation value that changes the size or shape of Node2D extensions.

Spatial Properties
> Location measured in meters

> Transform: An object containing a matrix of 12 numbers (Matrix 32) for the
scaling, rotation direction (pitch,yaw,roll) and Vector3 origin (xo,yo,zo).
> Translation: Local Vector3 offset, relative to parent scene center.
> Rotation Degrees: Pitch, Yaw, and Roll angle values.
> Scale: Value that modifies the size and shape of nodes and compatible components.

> transform - Local Direction (rotation), Skew, and Vector3(x,y,z) location.
> transform.origin - Local Transform Translation value, or offset value, relative to scene center
> transform.basis - Local rotation direction (x,y,z), axis-vectors rotated by local rotation
> get_transform() - Get local coordinates inside the parent object's coordinate space

> get_global_transform() - Return Global Rotation, Coordinates, Skew
> get_global_transform().origin - Return Global Spatial Vector3 Location
> get_global_transform().basis - Return Global Spatial Rotation Direction

> translation - Local Vector3 Offset, relative to parent node
> get_translation() - Return Local Vector3 Offset
> translate(Vector3(x,y,z)) # position += Vector3(x,y,z)
> global_translate(Vector3(x,y,z))

> rotation_degrees - Local Rotation Angle in Degrees
set_rotation()

> dot() = Get direction of two coordinates,
return 1 if both are in same direction
return 0 if 90 degree angle between the two,
return -1 if 180 degree angle between the two.

> cross() = 90 degree angle between two coordinates,
variable in parenthesis is normal,
should be a vector that makes a 90 degree
angle if drawn connecting another vector
from both points' translations to (0,0,0).

> adjacent, opposite, hypotanuse
> sin (0, theta) = opp/hyp
> cos (0, theta) = adj/hyp
> tan (0, theta) = opp/adj
> csc (0, theta) = hyp/opp
> sec (0, theta) = hyp/adj
> cot (0, theta) = adj/opp
================================================================

Example:
Imagine the Warthog from Halo; a 4-wheel military jeep with a
turret gun mounted on a rotating turret, attached in the bed
of the jeep.

Now imagine physical world space (Spatial Node), in which is
the Warthog (Child KinematicBody). Attached to the bed of the vehicle
is a Turret Gun (Child KinematicBody). The Warthog is (initially) facing
to negative z. The Turret is i.e. 1m (meters) back from the center (0,0,0) of the Warthog.
Then it's local origin is Vector3(0,1,0).

Now the Warthog itself is following a course and is rotated.
The turret is also rotated relative to the parent.
(Points in a different direction than the Warthog.)

If the turret turns, the values of its transform().basis will change.
If the Warthog moves and turns, the transform() of the turret won't change,
but the global_transform() will.

When the Warthog moves 10m forward, the Warthog's origin (global and local)
changes to (0,-10,0). The Turret's local origin stays the same (get_transform().origin)
but the global origin (get_global_transform().origin) changes accordingly to (0,-9,0)

If the Warthog turns instead 90° around the y-axis to the left,
the global origin of the Turret changes to (1,0,0). The local origin stays at (0,1,0)

Now you could get the local direction/rotation vector for z with:
get_transform().basis.z * -1
(-1 is only multiplied here to get the "forward" direction)
(The value above shows the relative positional offset 1m to the front of the (locally) rotated child.)

Useful for moving some other child object relative to the Turret in code.
Useful for raycasting and/or moving bullets/rockets.

===============================================================
[»] ORIGIN
===============================================================
It is a Vector 3 property with x/y/z coordinates.
In global context (get_global_transform().origin) is the
absolute coordinates in 3D context.
(Also known as translation vector)

If the object is a child object of another spatial,
get_transform() gets local coordinates inside the parent objects coordinate space.

This is the C++ code for translate:
# ===============================================================
# void Transform::translate(const Vector3 &p_translation) {

# for (int i = 0; i < 3; i++) {
# origin[i] += basis[i].dot(p_translation);
# }
# }
# ===============================================================

===============================================================
[»] BASIS
===============================================================
It is a rotation matrix property which determines Spatial orientation.
Most of the time, you might want to use the global rotation direction.

Basis has three member variables (x, y, z) that return normalized:
front, right, and up vectors. There's also the Basis.get_euler().

"basis.x" - Left/Right rotation
"basis.y" - Up/Down rotation

If your object "looks" forward in the direction of its local z-axis
then the forward vector should be:
get_global_transform().basis.z.normalized()

This is a Matrix32. It contains 3 x Vector3. One for each axis.
These vectors tell where the original x/y/z Vectors point after the rotation.
Object rotation neutral, pointing forward (no rotation):
basis.x = Vector3(1,0,0)
basis.y = Vector3(0,1,0)
basis.z = Vector3(0,0,1)

You rotate the object 90° to the left (around y-axis) then the values are like this
basis.x = Vector3(0,0,-1)
basis.y = Vector3(0,1,0)
basis.z = Vector3(1,0,0)

The columns of a rotation matrix can be thought as the local axes of the
coordinate system "painted" on the object, so it's typically
called "basis" in game engines.

Where basis is a Basis [Matrix3], and the bracket operator [] is
overloaded to return the Vector3 elements that makeup the matrix.
Going to the scale method in the Basis class, we can see that scale
is applied immediately to the Vector3 elements that make the matrix,
so all the elements are pre-scaled by the time we do the calculation
in translate. As such, 'translate' can't multiply the distance by the
scale, as the origin and current translation have already had the
scale baked in so to speak.

Angles vs. vectors:
You have to get used to the aspect that the direction is defined by
vectors and not by angles. There are reasons for this (gimbal lock) which
I won't (and probably can't) detail here. You should just avoid angles as much
as possible when calculation with rotation in 3D as you often won't get usable
results. Generally it should be ok to use set_rotation() on spatials but don't
expect to get the same angles back on get_rotation() ;-)

These methods basically all do the same:
Spatial (and descendants):
void look_at ( Vector3 target, Vector3 up )
void look_at_from_pos ( Vector3 pos, Vector3 target, Vector3 up )
Transform:
Transform looking_at ( Vector3 target, Vector3 up )

This methods calculates the Transform.basis (rotation) matrix which is needed to let the forward vector (Vector3(0,0,-1)) point from Transform.origin to the target coordinates. The "up" Vector defines the orientation of the resulting Transform.basis.

Example:
You have a node with a "head" mesh. When you let that head "look_at" another node and you pass a down-vector (Vector3(0,-1,0)) then the hair will be below the head. If you pass an up-vector (Vector3(0,1,0)) then the hair will be on the upside of the head. In any way the head will always point in the right direction, only the orientation is different.

basis:

A matrix of 3 x Vector3. It contains the (normalized) direction vectors of X/Y/Z-Axis.
B.t.w.: "normalized" means a vector is scaled to length 1

basis.z therefore is a Vector3 that contains the direction of the Z-Axis

This basically defines the rotation of a Transform. A single component (i.e. transform.basis.x) will give you the direction but not the orientation (where's the upside of the object/transform?).
global/local:

================================================================================

Single Line Comments/Remarks:
GDScript: #
C#: //
C++ : //

Multiline Comments/Remarks:
GDScript: """ """ (works only in v3.0 otherwise highlight comments and press ctrl+/)
C#: /* */
C++: /* */ or /* //*/
Strings:
GDScript: var myString = "Hello World" // (no Line Ending Symbol)
C#: string myString = "Hello World";
C++: char myString[] = "Hello World";

Integers:
GDScript: var myInt = 0 //(No Line End Symbol)
C#: int myInt = 0;
C++: int myInt = 0; // (remember about Integer/String and Char length restrictions in C++)
Floats:
GDScript: var myFloat = 0.1 //(Again No Line Ending)
C#: float myFloat = 0.1;
C++: float myFloat = 0.1; // Don't forget to ensure it does not exceed length limit.

Booleans:
GDScript: var myBool = true //(no line ending symbol)
C#: bool myBool = true;
C++: bool myBool = true;
Constants:
GDScript: const myConstant = 500 //(no line ending symbol)
C#: const int myInt = 0;
C++: const int myInt = 0;

Arrays:
GDScript: var myArray = ['String',1,true,0.1,"Other String"]
C#: int[] myIntArray = {0,1,2,3,4,5,6,7,8,9,10}; //must be of declaration type.
C++: int myIntArray[] = {0,1,2,3,4,5,6,7,8,9,10}; //must be of declaration type.
Dictionaries:
GDScript: var myDictionary ={
"One": 1,
"Two": 2,
"Three": 3
}

C#: Dictionary<string, string> myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
}; // can change either of types defined in Dictionary <string, string> so you may use and int and an int instead or a string and an int.

C++: std::map<int, std::string> myDictionary; // same rules apply from C# regarding the types defined.


ALL INFO ADJUSTED FOR GODOT 3.0.6 USAGE, ALL INFO SUBJECT TO CHANGE

ALL INFO IS GATHERED FROM OTHER SOURCES, ALL CREDIT TO AUTHORS

I CLAIM NO CREDIT, I AM COMPILING INFORMATION AVAILABLE

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License