D3/Autoload/time_screen_controller.gd
2025-05-10 23:19:52 +08:00

88 lines
2.4 KiB
GDScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

extends Node
## 用于控制时间速度和屏幕变暗效果的自动加载单例
const DEFAULT_TIME_SCALE := 1.0
const FADE_DURATION := 0.03 # 渐变效果持续时间
const SLOW_DURATION := 0.05 # 减速效果持续时间(当前未使用,保留)
const MAX_DARKNESS := 0.5 # 最大变暗程度0.0完全透明1.0完全黑)
var _current_time_scale := DEFAULT_TIME_SCALE
var _fade_overlay: ColorRect
var _is_fading := false
var _current_tween: Tween
var _should_maintain_slow := false # 是否保持减速状态
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS
_setup_fade_overlay()
func _setup_fade_overlay() -> void:
var canvas_layer := CanvasLayer.new()
canvas_layer.layer = 128
add_child(canvas_layer)
_fade_overlay = ColorRect.new()
_fade_overlay.color = Color(0, 0, 0, 0)
_fade_overlay.set_anchors_preset(Control.PRESET_FULL_RECT)
canvas_layer.add_child(_fade_overlay)
## 主控制函数:同时控制减速和变暗效果
## @param slow_time_scale: 时间缩放值1.0为正常速度小于1.0为减速)
## @param fade: 是否启用变暗效果
func execute_effects(slow_time_scale: float, fade: bool) -> void:
_kill_current_tween()
if slow_time_scale != DEFAULT_TIME_SCALE:
_slow_time(slow_time_scale)
else:
_reset_time()
_fade_to(MAX_DARKNESS if fade else 0.0)
## 立即恢复所有效果到正常状态
func reset_all() -> void:
_kill_current_tween()
_reset_time()
_is_fading = false
_fade_overlay.color.a = 0.0
# region 内部工具函数
func _kill_current_tween() -> void:
if _current_tween and _current_tween.is_valid():
_current_tween.kill()
func _set_time_scale(scale: float) -> void:
_current_time_scale = scale
Engine.time_scale = scale
func _slow_time(scale: float) -> void:
_set_time_scale(scale)
_should_maintain_slow = true
func _reset_time() -> void:
_set_time_scale(DEFAULT_TIME_SCALE)
_should_maintain_slow = false
func _fade_to(target_alpha: float) -> void:
if _is_fading:
return
_is_fading = true
_current_tween = create_tween()
_current_tween.tween_property(_fade_overlay, "color:a", target_alpha, FADE_DURATION)
_current_tween.tween_callback(func(): _is_fading = false)
# endregion
## 获取当前时间缩放值
func get_current_time_scale() -> float:
return _current_time_scale
## 检查是否正在执行渐变
func is_fading() -> bool:
return _is_fading
## 检查是否处于减速状态
func is_time_slowed() -> bool:
return _should_maintain_slow