godot4制作2D游戏12———用户界面
新建用户场景
- 创建一个canvasLayer节点作为新的PlayerHud场景
- 在下面创建一个Control节点
- 在Control节点下创建一个Sprite节点,导入素材
- 在Control下面创建一个HFlowContainer节点
- 在HFlowContainer节点下创建一个Control,作为HeartGUI场景
- 编写脚本heart_gui.gd并在其节点下添加Sprite子节点
1
2
3
4
5
6
7
8
9
10
11
12
13class_name HeartGUI extends Control
var value: int = 2 :
set (_value):
value = _value
update_sprite()
func update_sprite() -> void:
sprite.frame = value
pass
- 添加PlayerHud到AutoLoad
- 添加PlayerHud的脚本文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32extends CanvasLayer
var hearts: Array[HeartGUI] = []
func _ready() -> void:
for heart in $Control/HFlowContainer.get_children():
if heart is HeartGUI:
hearts.append(heart)
heart.visible = false
pass
func update_hp(_hp: int, _max_hp: int) -> void:
update_max_hp(_max_hp)
for i in _max_hp:
update_heart(i, _hp)
pass
func update_heart(_index: int, _hp: int) -> void:
var _value = clampi(_hp - _index * 2, 0, 2)
hearts[_index].value = _value
pass
func update_max_hp(_max_hp: int) -> void:
var _count: int = roundi(_max_hp * 0.5)
for i in _max_hp:
if i < _count:
hearts[i].visible = true
else:
hearts[i].visible = false
pass
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Have a nice day!!