跳到主要内容

GDScript Cheatsheet

Numbers

# Integers
var a = 1
var b = -23
var c = 0
var d = 0xA1Fe316 # hexadecimal

# Floats
var x = 1.0
var y = -43.01
var z = 1.3e6

# Constant
const THE_ANSWER = 42

# Pre-defined constants
PI # 3.14159265358979
TAU # 6.28318530717959
INF # infinity

Variables

var score = 0
var remaining_fuel = 99.9
var paused = false
var player_name = ""
var selected_weapon
var starting_grid_position
TypeDetailsExamples
intA 64bit signed number-12 54 0xAF
floatFloating point number1.23 1e6
boolTrue or falsetrue false
StringFor words and character sequences"Hello World"

Typed Variables

# Method 1
var score: int = 0
var remaining_fuel: float = 99.9
var paused: bool = false
var player_name: String = ""

# Method 2 (inferring the type)
var my_int := 8
var size := 32.6
var running := true
var name := ""

Operators

Mathematical Operators

OperatorDescription
-xNegation
* / %Times / Divide / Remainder
+Add
-Subtract
ExampleEquivalent Operation
x += 1x = x + 1
x -= 1x = x - 1
x *= 2x = x * 2
x /= 2x = x / 2
x %= 3x = x % 3

Boolean Operators

OperatorsDescription
< == > != >= <=Comparison operators
! notNOT
&& andAND
|| orOR

Bitwise Operators

OperatorDescription
~NOT (inverts the bits)
<< >>Shift bits of left-side operand left or right by n positions (1 << 2 == 4)
&Logical AND of two values
^Logical XOR of two values
|Logical OR of two values
&= |=Assignment shortcuts

Functions

extends Node2D

# Declare member variables here.
var player
var enemies
var score

# Called when the node enters the scene tree for the first time.
func _ready():
add_enemies()
get_player_details()

func add_enemies():
pass # Add code to do this later

func get_player_details():
pass # Add the code later

# Called every frame.
func _process(delta):
process_inputs(delta)
process_enemy_activity(delta)
update_score()

func process_inputs(delta):
pass

func process_enemy_activity(delta):
pass

func update_score():
pass
extends Node2D

# Called when the node enters the scene tree for the first time.
func _ready():
add(5, 6) # Prints 11 to Output window
var sum = get_sum(2, 4) # Sets sum to 6
var my_int = add_ints(sum, 4) # Sets my_int to 10
my_int = times_2(my_int) # sets my_int to 20
move_x(self, my_int) # Move this node 20 pixels along x axis
move_x(self) # Move by the default value

# This function has no return value
func add(a, b):
print(a + b)

# This function returns a value
func get_sum(a, b):
return a + b

# This function will only accept integer arguments
func add_ints(a: int, b: int):
return a + b

# Generate an error if the return value is not an int
func times_2(n) -> int:
return 2 * n

# This function modifies an object that is passed by reference
func move_x(node: Node2D, dx = 1.5):
node.position.x += dx

Conditional Statements

extends Node2D

func _ready():
var n = 6

# Inline 'if' statement
if n == 6: print("n is equal to six")

n = 4
# Regular 'if' statement
if n == 4:
print("n is equal to four")

# 'else/if' statement
if n == 6:
print("n is equal to six")
else:
print("n is not equal to six")

# Messy indented 'else/if' statement
if n == 6:
print("n is equal to six")
else:
if n < 6:
print("n is less than six")
else:
print("n is greater than six")

n = 8
# Tidier 'else/if' statement using 'elif'
if n == 6:
print("n is equal to six")
elif n < 6:
print("n is less than six")
else:
print("n is greater than six")

Ternary-if Expressions

var x = [value] if [expression] else [value]
var paid = false
var strength = 9.9 if paid else 1.0
print("Strength = ", strength)

Looping

For Loop

# loop for n = 0 to 7
for n in 8:
print(n)

# Using range
for n in range(8):
print(n)

# loop for n = 10 to 12
for n in range(10,13):
print(n)

# count down from 10 to 1
for n in range(10,0,-1):
print(n)

# loop for n = 2,4,6,8 in steps of 2
for n in range(2,9,2):
print(n)

# Iterate over string (array of characters)
for ch in "Hello":
print(ch)

# Iterate over an array of numbers
for x in [3,6,8,9]:
print(x)

# Iterate over items of a dictionary
var dict = { "x": 1, "y": 2, "z": 3 }
for key in dict:
# Insert the key and value into a text string
print("index: %s, value: %d" % [key, dict[key]])

# Using continue and break statements
for n in 9:
# Skip numbers below 3
if n < 3:
continue
# Break out of the loop for numbers above 5
if n > 5:
break
print(n)

While Loop

var fuel = 1000
var speed = 0

while fuel > 0:
speed += 0.12
fuel -= 1

print("Top speed = ", speed)

Arrays

extends Node2D

func _ready():
# Ways to create an array instance
var a = Array()
var b = []
var c = ["a","b","c"]

# Add some items to array 'a'
a.append("Item 1")
a.append("Item 2")

# Pass array by reference to a function
change(a)
# Confirm that changes were made
print(a[0])

# Print the size of array 'b'
print(b.size())

# Shuffle the values of array 'c'
c.shuffle() # This function doesn't return a value
# Check that the element order was changed
print_elements_of(c)

func change(a):
a[0] = 1

func print_elements_of(array):
# Here we are using one of the Pool array types
print(PoolStringArray(array).join(""))

Dictionaries

extends Node2D

# Declare an empty dictionary object
var game = {}

func _ready():
# Initialize a player dictionary
var player = {
"name": "Thor",
"inventory": ["sword", "shield", "map"],
"location": "Castellion",
"energy": 67
}

if game.empty():
# Add data to the game dictionary
game["player"] = player
game["score"] = 0
game["dummy"] = null

if game.has("dummy"):
game.erase("dummy")

print(game.get("dummy", "Key not found!"))

if game.has_all(["player", "score"]):
print(game["player"]["name"])

player["energy"] += 1

print(game.keys().size())
print(game.size())
print(player.values()[0])

# Alternative way to initialize a dictionary
var d = {
a = {
a1 = {
a11 = 1, a12 = 2
},
a2 = 3
},
b = 1
}

# Make copies of the dictionary
var deep_copy = d.duplicate(true)
var shallow_copy = d.duplicate()
print(deep_copy)
# I expected the shallow copy to be truncated
print(shallow_copy)

Classes

class_name Motorcycle extends Node2D

# Add properties
export(String) var make = "Kawasaki"
export(int) var cc = 900
export(Color, RGB) var color = ColorN("Ninja Green")
var fuel = 0.0
var speed = 0.0

# Override virtual methods
func _ready():
add_fuel(17.3)

func _process(delta):
if fuel > 0.0:
speed += delta
fuel -= delta
print(speed, "km/h")

# Add a new method
func add_fuel(litres):
fuel += litres

参考资料