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

HaxeFlixel中计时器仅在计数结束时显示数值的问题求助

解决计时器仅显示最终数值的问题

你的核心问题出在update函数里的while循环——游戏引擎的渲染逻辑是在每帧update执行完毕后才触发的。这个while循环会在一帧内直接把count从0跑到10,中间所有updateCounter的调用都只是修改了内存中的值,但屏幕根本没机会刷新,直到循环结束才会渲染最后一次的数值(10)。


1. 替换update里的while为if

因为update函数本身就是引擎逐帧调用的(通常每秒60次),不需要用循环来持续计数,只需要在每帧检查是否满足计数条件即可:

override public function update(elapsed:Float)
{
    super.update(elapsed);
    // 把while改成if,避免一帧内跑完所有计数
    if (counterStarted == true && count < 10)
    {
        today = Date.now();
        second = today.getSeconds();
        if (second != lastSecond)
        {
            lastSecond = second;
            count++;
            counter++;
            counterHud.updateCounter(counter);
            trace(count);
            trace("second was != last second");
        }
    }
}

注:修正了代码里的secound拼写错误。

2. 修复updateCounter的重复添加问题

你现在每次调用updateCounter都会执行add(background)和add(textcounter),这会导致屏幕上堆积大量相同的显示对象,不仅浪费性能,还可能导致显示异常。应该只在初始化时添加一次,之后只更新内容:

// 初始化时执行一次(比如在类的构造函数里)
add(background);
add(textcounter);

public function updateCounter(counter:Int)
{
    background.drawRect(0, 19, FlxG.width, 1, FlxColor.CYAN);
    textcounter.text = Std.string(counter);
    textcounter.x = textcounter.width - 4;
    // 不需要重复add
    trace("In updateCounter:" + counter);
}

额外优化:用引擎时间系统替代Date

用Date.getSeconds()可能会遇到秒数跳变的问题(比如刚好跨分钟时),建议用Flixel内置的时间系统来计算,更精准:

private var timer:Float = 0;
private var lastCountTime:Float = 0;

override public function update(elapsed:Float)
{
    super.update(elapsed);
    timer += elapsed;
    if (counterStarted == true && count < 10)
    {
        // 每1秒计数一次
        if (timer - lastCountTime >= 1)
        {
            lastCountTime = timer;
            count++;
            counter++;
            counterHud.updateCounter(counter);
            trace(count);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:43:17