banner
音小董

哩哔哩哔

这世上的热闹出自孤单

Game development GdScript scripting language

Section 1: Understanding GdScript#

Godot uses GdScript as a scripting language to control game objects with code.

  • Because GdScript is a weakly-typed language, it provides more freedom. However, we can establish some principles to make the code more standardized:
Class names must be the same as file names and in lowercase.
Try to inherit from the Node2D node, as the Transform in Node2D is the most commonly used node.
  • Commonly used function execution order: _init, _ready, _process
Some event functions are defined by default, such as:
  _init(): Called when the script is initialized, similar to the constructor in Java.
  _ready(): Called once at the beginning, used for script initialization.
  _process(delta): Called every frame, with varying frame intervals, used for updating the game.

Section 2: Variables and Data Types#

  • Variables are "containers" used to store information.
var x = 5;
var y = 6;
var z = x + y;

Just like in algebra:
x = 5
y = 6
z = x + y

In algebra, we use letters (like x) to store values (like 5).
With the expression z = x + y, we can calculate that the value of z is 11.
In Godot, these letters are called variables.
  • The Export keyword allows variables to be edited in the editor.
# Export a number
@export var a = 1
# Export a node path
@export var b:NodePath
# Export a node path, alternative syntax
@export(NodePath) var c
# Export a file path
@export(String, FILE) var e 
# Export a file path with .txt extension
@export(String, FILE, "*.txt") var d
# Export a resource file path
@export(Resource) var f
# Export a color
@export(Color, RGB) var g
  • GdScript data types:
    • Bool: 1 byte, default value is false.
    • Int (same as long in C++ and Java): 8 bytes, default value is 0.
    • Float (same as double in C++ and Java): 8 bytes, default value is 0.
    • String: Default value is null. Strings can store a series of characters, such as "John Doe".
    • Array
    • Object
    • Null: If a variable is not assigned a value, its default value is null.

Section 3: Functions#

  • Functions can be understood as reusable code blocks that are executed when called.
  • A function is a code block enclosed in curly braces, preceded by the keyword func. When the function is called, the code inside the function is executed.
  • Empty functions use the pass keyword.
func sayHello():
    # Code to be executed
  • Calling a function with parameters allows you to pass values to the function. These values are called arguments.
func sayHello(param1, param2):
    # Code to be executed
  • Functions with return values allow you to return a value to the place where the function is called. This can be achieved using the return statement. The return type can be specified.
func sayHello(param1, param2):
    # Code to be executed
    return x

Section 4: Variable Scope#

  • Local scope: Variables declared inside a function have local scope and can only be accessed within the function.
# carName variable cannot be accessed here
func myFunction():
    var carName = "Volvo";
    # carName variable can be accessed here
  • Global scope: Variables defined outside a function have global scope and can be accessed throughout the entire script file.
var carName = "Volvo";
 
# carName variable can be accessed here
func myFunction():
    # carName variable can be accessed here

Section 5: Operators#

  • Arithmetic operators:
+	Addition	x = y + 2	7	5
-	Subtraction	x = y - 2	3	5
*	Multiplication	x = y * 2	10	5
/	Division	x = y / 2	2.5	5
%	Modulus	x = y % 2	1	5
  • Assignment operators: Used to assign values to GdScript variables.
=	x = y	 	x = 5
+=	x += y	x = x + y	x = 15
-=	x -= y	x = x - y	x = 5
*=	x *= y	x = x * y	x = 50
/=	x /= y	x = x / y	x = 2
%=	x %= y	x = x % y	x = 0
  • Comparison operators: Used in logical statements to determine whether variables or values are equal.
==	Equal	x == 8	false
!=	Not equal	x != 8	true
>	Greater than	x > 8	false
<	Less than	x < 8	true
>=	Greater than or equal to	x >= 8	false
<=	Less than or equal to	x <= 8	true
  • Logical operators: Used to determine the logic between variables or values.
&&	and	(x < 10 && y > 1) is true
||	or	(x == 5 || y == 5) is false
!	not	!(x == y) is true

Section 6: Conditional Statements#

  • Conditional statements are used to execute different actions based on different conditions in code.

  • if statement: Executes code only if a specified condition is true.

if (condition):
    Code to be executed when the condition is true
  • if...else statement: Executes code if a specified condition is true, and another code if the condition is false.
if (condition):
    Code to be executed when the condition is true
else:
    Code to be executed when the condition is false
  • if...else if...else statement: Selects one of several code blocks to be executed.
if (condition1):
    Code to be executed when condition1 is true
elif (condition2):
    Code to be executed when condition2 is true
else:
    Code to be executed when both condition1 and condition2 are false
  • match (switch) statement: Selects one of several code blocks to be executed.

Section 7: Loop Statements#

  • Loops allow you to repeatedly execute a code block for a specified number of times. If you want to run the same code over and over again, with each time having a different value, loops are very convenient.
  • for loop
  • while loop
  • The break statement exits the loop and continues executing the code after the loop (if any).
  • The continue statement interrupts the current iteration of the loop if a specified condition occurs, and continues with the next iteration of the loop.

Section 8: Traversing Arrays and Dictionaries#

  • Traversing arrays:
func arrayIterator():
	# range is equivalent to for(int i = 0; i < 20; i++)
	print("Array traversal method 1:")
	for i in range(3):
		print(i)
	print("Array traversal method 2:")
	for ele in arr:
		print(ele)
	print("Array traversal method 3:")
	for index in range(arr.size()):
		print(arr[index])
  • Traversing dictionaries:
func dictionaryIterator():
	print("Dictionary traversal method 1:")
	for key in dict:
		print("key: " + key as String)
		print("value: " + dict[key] as String)
		
	print("Dictionary traversal method 2:")
	for key in dict.keys():
		print("key: " + key as String)
		print("value: " + dict[key] as String)
		
	print("Dictionary traversal method 3:")
	for value in dict.values():
		print("value: " + value as String)	

Section 9: Static Variables and Methods#

  • Const variables (static variables):
const ANSWER = 42
  • Static methods:
static func getAnswer():
	return ANSWER

Section 10: Objects#

  • Objects in real life have properties and methods.
  • In real life, a car is an object. It has properties like weight and color, and methods like start and stop.
# Inner class, inherits from Object by default
class Animal:
	extends Object  # If the inherited class is not specified, it defaults to Object.
	const STATIC_FIELD = "Static variable"
	# Properties
	var height: int
	
	func _init():
		print("Animal constructor")
		
	func move():
		print("Animal moves")
	
	static func staticFunction():
		pass

Section 11: Node Access Methods#

# Get current node
var currentNode1 = $"."
var currentNode2 = self

# Get parent node
var parentNode1 = get_parent()
var parentNode2 = $"../"

# Get child node
var subNode1 = $SubNode2
var subNode2 = $"SubNode2"
var subNode3 = get_node("SubNode2")

# Root node lookup, returns the first node found in the node tree from top to bottom
var subNode4 = get_tree().root.find_node("SubNode2", true, false)

Section 12: Signals#

  • Signals are used as a means of communication between modules or functionalities. They define the callback form of certain methods.

  • This design pattern is called the Observer design pattern.

1. The observer and the observed are abstractly decoupled, decoupling modules.
2. Establish a unified triggering mechanism.
  • The Godot engine officially recommends using signals more in your game development to achieve communication between modules or functionalities.

  • First method of using signals:

# First method of signal reception, by configuring the signal reception method in the scene
func _on_Button1_pressed():
	print("Hello button1")
  • Second method of using signals:
# Second method of signal reception, by controlling the signal reception through code, more flexible and recommended
func _ready():
	$Button2.connect("pressed", self, "onButton2")
	
func onButton2():
	print("Button2 pressed")

Section 13: Custom Signals#

  • Custom signals
signal mySignal(a, b)
  • Emitting signals
emit_signal("mySignal", 1, 2)
  • Disconnecting signals
disconnect("mySignal", 1, 2)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.