菜单
这节我们为游戏添加一个主菜单,提供进入游戏、加载游戏、退出游戏的入口。

创建节点
新建节点,选择用户界面。
创建如下节点:
py
Control GUI控件的基类。
|-TextureRect 显示控件,背景
|-TextureRect 菜单
|-VBoxContainer 容器,方便排列按钮
|-Button 按钮
|-Button
|-Button
然后我们设置一下节点的属性,调整视觉效果。
1、背景:在TextureRect-Texture下面加载背景图片。在Control->Layout->Transform下面调整Scale控制图片尺寸。
2、菜单:和背景操作相同,加载菜单图片、调整尺寸。
3.1、VBoxContainer和Button:把3个Button的对垂直齐设置里面的扩展都打开,然后调整VBoxContainer的Separation属性,使得三个按钮刚好和菜单图片对齐。

3.2、设置按钮效果:为按钮添加3种效果:
- 默认灰色
- 选中时增加一个框
- 按下时发亮。

这可以在按钮的 Control->Theme Overrides->Styles进行设置。设置其中的Normal、Hover为空、Pressed、Focus为我们想要的图片。

创建完节点并设置完属性后,我们就有了一个可用的菜单了,而且已经支持键盘上下和空格的按键了。接下来我们把具体的逻辑和按钮按下的信号关联。
关联脚本
为场景关联一个脚本main_menu.gd:为了手感更好一些,我们加了一个定时器,当玩家按下按钮后,等待0.5s后才执行功能,跳转到游戏界面。新建游戏、加载游戏、退出的逻辑和之前的类似。
py
extends Control
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
get_node("menu/VBoxContainer/Button1").grab_focus()
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
func _on_newgame_button_1_pressed() -> void:
$start.start()
func _on_loadgame_button_2_pressed() -> void:
$load.start()
func _on_quit_button_3_pressed() -> void:
$quit.start()
func _on_start_timeout() -> void:
FileExport.new_game()
get_tree().change_scene_to_file("res://scenes/world.tscn")
func _on_load_timeout() -> void:
if ResourceLoader.exists(FileExport.PATH):
FileExport.load_game()
global.loading = true
get_tree().change_scene_to_file("res://scenes/camp.tscn")
else:
FileExport.new_game()
get_tree().change_scene_to_file("res://scenes/world.tscn")
func _on_quit_timeout() -> void:
get_tree().quit()