You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Timer节点time_left初始为0导致逻辑异常的优化方案咨询

问题解决方法

问题根源很明确:场景加载后,Timer默认处于未启动状态,此时time_left的值就是0,你的_process每帧都在轮询这个值,导致场景刚加载就触发了原本要等倒计时结束才执行的逻辑。

下面是两种正确的修复方式,更推荐第一种:

方式一:使用Timer的timeout信号(官方推荐)

Timer的设计初衷就是通过timeout信号来通知倒计时结束,完全不需要手动轮询time_left,从根源避免初始值问题。

  1. 先移除_process里的那段轮询代码,然后添加信号处理逻辑:
func _ready():
    # 把Timer的timeout信号连接到我们的处理函数
    $turn_timer.connect("timeout", self, "_on_turn_timer_timeout")

# 专门处理Timer倒计时结束的函数
func _on_turn_timer_timeout():
    if e_next_move == 1:
        e_is_attacking = true
    else:
        turn_end()

    if e_health > 0:
        e_nextmove()
    else:
        e_next_move = 0
        $enemy.hide()
    
    # 因为你设了one_shot模式,Timer触发后会自动停止,这里手动stop也不影响
    $turn_timer.stop()
  1. 之后在需要启动3秒倒计时的时机(比如回合开始时),直接调用:
$turn_timer.start()

方式二:给轮询条件加判断(临时兼容方案)

如果你不想改动太多代码,可以在原来的判断里加上Timer是否处于激活状态的检查,因为未启动的Timeris_active是false,只有正在运行的Timer倒计时到0才会触发逻辑:

func _process(delta):
    # 加上is_active()判断,只有运行中的Timer倒计时到0才执行
    if $turn_timer.time_left == 0 and $turn_timer.is_active():
        if e_next_move == 1:
            e_is_attacking = true
        else:
            turn_end()

        if e_health > 0:
            e_nextmove()
        else:
            e_next_move = 0
            $enemy.hide()
        $turn_timer.stop()

之后正常调用$turn_timer.start()启动3秒倒计时即可,不用再传999这种奇怪的参数。

内容的提问来源于stack exchange,提问作者TraitPhoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 08:37:48