我如何在 Godot 中创建一个计时器,它会在给定的时间后销毁脚本的对象?我希望在一段时间后从游戏中移除子弹以减少延迟。
有一个
Timer
节点可以使用。您可以将其添加为子项,设置等待时间(以秒为单位)-您可能将其设置为一次拍摄并自动启动-将"timeout"
信号连接到您的脚本,并在方法调用queue_free
上获得节点(和子节点,包括Timer
)安全释放。
你也可以从代码中做到这一点,如果你喜欢的话。那么,让我们回顾一下我刚才所说的内容,但不是从编辑器中进行,而是让我们看看等效的代码:
创建一个
Timer
,添加为子项:
var timer := Timer.new()
add_child(timer)
设置等待时间(以秒为单位):
timer.wait_time = 1.0
设置为单发:
timer.one_shot = true
与其将其设置为自动启动(这将是
timer.autostart = true
,让我们启动它:
timer.start()
将
"timeout"
信号连接到方法。在这种情况下,我将调用方法 "_on_timer_timeout"
:
timer.connect("timeout", self, "_on_timer_timeout")
func _on_timer_timeout() -> void:
pass
然后在那个方法
_on_timer_timeout
中,调用queue_free
:
timer.connect("timeout", self, "_on_timer_timeout")
func _on_timer_timeout() -> void:
queue_free()
你可能想使用
SceneTreeTimer
,就像下面的代码:
func die(delay: float):
yield(get_tree().create_timer(delay), "timeout")
queue_free()
请参考 Godot Engine 的文档.
在Godot 4中,有一个更简单的方法来做到这一点:
# Do some action
await get_tree().create_timer(1.0).timeout # waits for 1 second
# Do something afterwards
queue_free() # Deletes this node (self) at the end of the frame
但是,如果您在
_process()
或 _physics_process()
函数 中执行此操作,则每帧都会创建更多计时器,这会导致在运行以下代码之前同时运行多次。要处理这个问题,只需跟踪定时事件是否正在发生。
_process()
中的示例具有简单的攻击逻辑:
var attack_started = false;
func _process(delta):
if attack_started:
print("Not attacking, attack code running in background")
return
else:
attack_started = true
prepare_attack()
await get_tree().create_timer(1.0).timeout # wait for 1 second
begin_attack()
attack_started = false
这个
await
关键字适用于所有发出信号的东西,包括碰撞事件!
仅供参考:
yield
在 Godot 4 中被替换为 await
,await
实际上只是等待信号/回调完成:
await object.signal
get_tree().create_timer(5.0)
将创建一个运行 5 秒的计时器,然后有一个 timeout
回调/信号,您可以点击它。
建立杀戮的答案......
在 C# 中你可以写
await ToSignal(GetTree().CreateTimer(1.5f), "timeout");`
QueueFree();