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

2023-08-08 12:57:56 浏览数 (2)

类型推断

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

代码语言:javascript复制
var life_points := 4
var damage := 10.5
var motion := Vector2()

数组

代码语言:javascript复制
var array = [10, "hello", 40, 60] # Simple, and can mix types
array.resize(3) # Can be resized
use_array(array) # Passed as reference

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

代码语言:javascript复制
var array = []
array.append(4)
array.append(5)
array.pop_front()

或无序集:

代码语言:javascript复制
var a = 20
if a in [10, 20, 30]:
    print("We have a winner!")

字典

字典示例:

代码语言:javascript复制
var d = {"name": "John", "age": 22} # Simple syntax
print("Name: ", d["name"], " Age: ", d["age"])

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

代码语言:javascript复制
d["mother"] = "Rebecca" # Addition
d["age"] = 11 # Modification
d.erase("name") # Removal

遍历

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

代码语言:javascript复制
for s in strings:
    print(s)

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

代码语言:javascript复制
for key in dict:
    print(key, " -> ", dict[key])

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

代码语言:javascript复制
for i in range(strings.size()):
    print(strings[i])

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

代码语言:javascript复制
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

正向遍历

代码语言:javascript复制
for i in range(10):
    pass

for i in range(5, 10):
    pass

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

反向遍历

代码语言:javascript复制
for i in range(10, 0, -1):
    pass

字符串

单个占位符

代码语言:javascript复制
# 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

代码语言:javascript复制
# 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"

多个占位符

代码语言:javascript复制
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."

混合

代码语言:javascript复制
"Hi, {0} v{version}".format({0:"Godette", "version":"%0.2f" % 3.114})

类与对象

实例化

代码语言:javascript复制
AudioStreamPlayer.new()

类型转换

代码语言:javascript复制
Sprite mySprite = GetNode("MySprite") as Sprite;
// Only call SetFrame() if mySprite is not null
mySprite?.SetFrame(0);

0 人点赞