GDScript学习笔记

相关视频链接:YouTube(生肉),bilibili(熟肉)

https://www.bilibili.com/video/BV1fx4y1p79u/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=e25b71d6c243cef702fd4b55b7792d99


该文章只记录关键信息,具体操作请看视频
我用的版本:4.3

GDScript语言整体和Python与javascript很像

修改节点1.0

使用一个标签(Label)节点

func _ready():
	$Label.text = "Hello world!"
	$Label.modulate = Color.BLUE

$Label 用于获取标签节点(名字可能不同)
.text 用来获取text属性
.modulate 用来获取颜色属性
Color.BLUE 是预设的颜色

输入/Input

先进行绑定按键操作

func _input(event):		#接受任何输入时会调用的函数
	if event.is_action_pressed("my_action"):
		$Label.modulate = Color.RED

	if event.is_action_released("my_action"):
		$Label.modulate = Color.BLUE

该程序使玩家在按下特定按键时使标签变为红色,松开时变为蓝色

event 事件,包含了触发该函数的信息
_input(event) 输入的事件
event.is_action_pressed() 按钮是否被按下
event.is_action_released() 按钮是否被松开

if语句

和python相同

变量

创建变量(注意全局变量和局部变量的区别)

var health = 100
var damage: int = 20
const GRAVITY = -9.81
var vec2 = Vector2(2.0, 2.0)
var vec3 = Vector3(3.0, 3.0, 3.0)

第一行定义了一个health变量
第二行定义了一个整数类型的damage变量
第三行定义了一个常量GRAVITY
Vector2储存两个浮点数x,y
Vector3储存三个浮点数x,y,z

函数

func _input(event):
	if event.is_action_pressed("my_action"):
		jump()

func jump():
	print("Jump!")
func _ready():
	var result = add(3,5)
	print(result)

func add(num1: int, num2: int) -> int:   	# -> int 箭头表明返回值为整数
	var result = num1 + num2
	return result

随机数

func _ready():
	var roll = randf()
	if roll <= 0.8:
		print("You found a COMMON item.")
	else:
		print("You found a RARE item.")

	var height = randi_range(140,210)
	print("Your character is " + str(height) + "cm tall.")

randf() 随机0 ~ 1以内的数
randi_range(x ,y) 随机x ~ y以内的数

数组

和Python列表相同

循环,循环,循环……

for循环和while循环
berak语句和continue语句
和Python相同

字典

和Python相同

func _ready():
	var players = {
		"Crook": 1,
		"Villain": 35,
		"Boss": 100
	}

	print(players["Boss"])		#打印键的值
	players["Villain"] = 50		#修改值
	Players["Dwayne"] = 999		#添加键值对

	for username in players:
		print(username + ": " + str(players[username]))		#遍历字典
#字典的嵌套(使用缩进保持代码整洁)
func _ready():
	var players = {
		"Crook": 	{"Level": 1, "Health": 80}
		"Villain": 	{"Level": 50, "Health": 100}
		"Boss":		{"Level": 100, "Health": 500}
	}

	print(players["Boss"]["Health"])

枚举

本质是一堆值不断增加的常量

enum Alignment { ALLY, NEUTRAL, ENEMY }
#枚举   势力      盟友    中立    敌人   

@export var unit_alignment : Alignment
#这句将Unit Alignment 导出到右方的检查器上

func _ready():
	if unit_alignment == Alignment.ENEMY:
		print("You are not welcome here.")
	else:
		print("Welcome!")

可以更改枚举的默认值

enum Alignment { ALLY = 1, NEUTRAL = 0, ENEMY = -1 }

Match

相当于其他语言的 switch 语句
允许我们根据变量的值执行不同的代码

enum Alignment { ALLY, NEUTRAL, ENEMY }
#枚举   势力      盟友    中立    敌人   

@export var unit_alignment : Alignment

func _ready():
	match my_alignment:
		Alignment.ALLY:
			print("Hello friend.")
		Alignment.NEUTRAL:
			print("I come in peace.")
		Alignment.ENEMY:
			print("F**k you!")
		_:									#不是上述任何一种情况时
			print("Who are you?")

修改节点2.0

按住ctrl键拖动节点会自动创建一个带有节点名称和正确路径的变量

@onready var weapon = $Player/Weapon
# 关键词     节点名称      正确路径

$ 符号是函数 get_node() 的简写

@export var my_node: Node

该行会导出一个 My Node 变量到检查器上,方便分配节点

信号

信号是节点可以互相发送的信息
看原视频更好理解

singal level_up

var xp  := 0

func _on_timer_timeout():
	xp += 5
	print(xp)
	if xp >= 20
		xp = 0
		level_up.emit()

func _on_level_up():
	print("Level up!")

.emit() 发出信号

Get,Set

没看懂

signal health_changed(new_health)

var health := 100:
	set(value):
		health = clamp(value, 0, 100)	# 钳制health在0和100之间
		health_changed.emit(health)

func _ready():
	health := -100

func _on_health_changed(nem_health):
	print(nem_health)
var chance := 0.2
var chance_pct: int: 
	get:
		return chance * 100
	set(value):
		chance = float(value) / 100.0

func _ready():
	print(chance_pct)
	chance = 0.6
	print(chance_pct)