89 lines
2.2 KiB
GDScript
89 lines
2.2 KiB
GDScript
extends Control
|
||
class_name VirtualButton
|
||
## 虚拟按钮控件
|
||
## 用于移动端触摸输入
|
||
|
||
# 按钮参数
|
||
@export var button_radius: float = 40.0
|
||
@export var button_text: String = "E"
|
||
|
||
# 按钮状态
|
||
var is_pressed_state: bool = false
|
||
var was_just_pressed: bool = false
|
||
var touch_index: int = -1
|
||
|
||
# 视觉元素
|
||
var button_circle: ColorRect
|
||
var label: Label
|
||
|
||
func _ready():
|
||
"""初始化虚拟按钮"""
|
||
_create_visual_elements()
|
||
|
||
# 设置大小
|
||
custom_minimum_size = Vector2(button_radius * 2, button_radius * 2)
|
||
size = custom_minimum_size
|
||
|
||
func _create_visual_elements():
|
||
"""创建按钮的视觉元素"""
|
||
# 创建按钮背景
|
||
button_circle = ColorRect.new()
|
||
button_circle.color = Color(0.2, 0.6, 0.2, 0.6)
|
||
button_circle.size = Vector2(button_radius * 2, button_radius * 2)
|
||
button_circle.position = Vector2.ZERO
|
||
add_child(button_circle)
|
||
|
||
# 创建文本标签
|
||
label = Label.new()
|
||
label.text = button_text
|
||
label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||
label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
|
||
label.size = Vector2(button_radius * 2, button_radius * 2)
|
||
label.position = Vector2.ZERO
|
||
label.add_theme_font_size_override("font_size", 24)
|
||
add_child(label)
|
||
|
||
func _process(_delta: float):
|
||
"""每帧更新"""
|
||
# 重置 just_pressed 状态
|
||
if was_just_pressed:
|
||
was_just_pressed = false
|
||
|
||
func _gui_input(event: InputEvent):
|
||
"""处理触摸输入"""
|
||
if event is InputEventScreenTouch:
|
||
if event.pressed:
|
||
# 触摸开始
|
||
is_pressed_state = true
|
||
was_just_pressed = true
|
||
touch_index = event.index
|
||
_update_visual(true)
|
||
elif event.index == touch_index:
|
||
# 触摸结束
|
||
is_pressed_state = false
|
||
touch_index = -1
|
||
_update_visual(false)
|
||
|
||
func _update_visual(pressed: bool):
|
||
"""更新按钮视觉状态"""
|
||
if pressed:
|
||
button_circle.color = Color(0.3, 0.8, 0.3, 0.8)
|
||
else:
|
||
button_circle.color = Color(0.2, 0.6, 0.2, 0.6)
|
||
|
||
## 检查按钮是否刚被按下
|
||
func is_pressed() -> bool:
|
||
"""
|
||
检查按钮是否刚被按下(类似 Input.is_action_just_pressed)
|
||
@return: 是否刚被按下
|
||
"""
|
||
return was_just_pressed
|
||
|
||
## 检查按钮是否正在被按住
|
||
func is_held() -> bool:
|
||
"""
|
||
检查按钮是否正在被按住
|
||
@return: 是否被按住
|
||
"""
|
||
return is_pressed_state
|