Godot进行2D游戏开发入门-GDScript基本语法

类型推断

如果编写冒号,Godot将尝试推断类型,但省略了类型:

1
2
3
var life_points := 4
var damage := 10.5
var motion := Vector2()

数组

1
2
3
var array = [10, "hello", 40, 60] # Simple, and can mix types
array.resize(3) # Can be resized
use_array(array) # Passed as reference

在动态类型语言中,数组也可以与其他数据类型(如列表)同时使用:

1
2
3
4
var array = []
array.append(4)
array.append(5)
array.pop_front()

或无序集:

1
2
3
var a = 20
if a in [10, 20, 30]:
print("We have a winner!")

字典

字典示例:

1
2
var d = {"name": "John", "age": 22} # Simple syntax
print("Name: ", d["name"], " Age: ", d["age"])

字典也是动态的,可以在任何地方添加或删除键,成本很低:

1
2
3
d["mother"] = "Rebecca" # Addition
d["age"] = 11 # Modification
d.erase("name") # Removal

遍历

支持数组,字典和字符串的遍历。

1
2
for s in strings:
print(s)

容器数据类型(数组和字典)是可重复的。字典允许迭代键:

1
2
for key in dict:
print(key, " -> ", dict[key])

也可以使用索引进行迭代:

1
2
for i in range(strings.size()):
print(strings[i])

range()函数可以接受3个参数:

1
2
3
range(n) # Will go from 0 to n-1
range(b, n) # Will go from b to n-1
range(b, n, s) # Will go from b to n-1, in steps of s

正向遍历

1
2
3
4
5
6
7
8
for i in range(10):
pass

for i in range(5, 10):
pass

for i in range(5, 10, 2):
pass

反向遍历

1
2
for i in range(10, 0, -1):
pass

字符串

单个占位符

1
2
3
4
5
6
7
8
# Define a format string with placeholder '%s'
var format_string = "We're waiting for %s."

# Using the '%' operator, the placeholder is replaced with the desired value
var actual_string = format_string % "Godot"

print(actual_string)
# Output: "We're waiting for Godot."

方式2

1
2
3
4
5
6
7
8
# Define a format string
var format_string = "We're waiting for {str}"

# Using the 'format' method, replace the 'str' placeholder
var actual_string = format_string.format({"str": "Godot"})

print(actual_string)
# Output: "We're waiting for Godot"

多个占位符

1
2
3
4
5
var format_string = "%s was reluctant to learn %s, but now he enjoys it."
var actual_string = format_string % ["Estragon", "GDScript"]

print(actual_string)
# Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."

混合

1
"Hi, {0} v{version}".format({0:"Godette", "version":"%0.2f" % 3.114})

类与对象

实例化

1
AudioStreamPlayer.new()

类型转换

1
2
3
Sprite mySprite = GetNode("MySprite") as Sprite;
// Only call SetFrame() if mySprite is not null
mySprite?.SetFrame(0);