Wait() in Haxe?

6
我正在学习Haxe和OpenFL,并且有一些Javascript和Lua的经验。
一切进展顺利,但是我遇到了一个问题,我需要类似于Lua中wait()的函数,该函数在你设置的秒数结束之前停止脚本运行。

我该如何解决这个问题?

编辑:为澄清起见,我正在构建Flash。

3个回答

5

虽然这篇文章有点老了,但我想再补充一点参考意见。评论中提到这是为游戏而写的。我经常使用的一种方法是(并且可能可以放入库中):

var timerCount:Float = 0;
var maxTimerCounter:Float = 5;

function update () {
    timerCounter += elapsedTime;
    if (timerCounter > maxTimerCounter){
        onTimerComplete();
        timerCount = 0;
    }
}

4

在SYS中,您需要寻找:

静态函数sleep(秒:浮点数):Void 暂停当前执行给定的时间(以秒为单位)。

例如:Sys.sleep(.5);

http://haxe.org/api/sys/

编辑:用户正在转移到Flash。

因此建议使用Timer。

http://haxe.org/api/haxe/timer

在计时器中,建议使用 静态函数delay(f:Void -> Void,time_ms:Int):计时器

stackoverflow上有一个示例,看起来像这样:haxe.Timer.delay(callback(someFunction,“abc”),10);位于此处...Pass arguments to a delayed function with Haxe


抱歉,我忘了提到我正在构建Flash,而Sys仅支持Neko、PHP、C++、CS和Java,因此当我尝试使用Sys.sleep()进行构建时,会出现“访问此字段需要系统平台(php、neko、cpp等)”的错误。 - IBPX
我知道你可以使用 haxe.Timer.delay(a, b)b 毫秒后执行 a,但是脚本的其余部分不会等待它。有没有类似于 this.stop()this.resume() 的组合可以使用? - IBPX
你需要延迟多久?是在等待进程还是等待用户输入? - Frank Tudor
我正在进行时间延迟(即尝试使用Haxe制作游戏)。 - IBPX
好的,这是我的当前Sleep()函数的代码(链接:http://pastebin.com/GVx7YzLe),但是在尝试构建时我一直收到“浮点数应该是整数”的错误提示。你看到我做错了什么吗? - IBPX
显示剩余6条评论

0
对于Flash编译目标,你能做的最好的办法就是使用一个定时器,类似于setTimeout()函数。 这意味着将你的函数分成两部分 - setTimeout()之前的所有内容和setTimeout()之后的内容,这部分内容放在一个单独的函数中供定时器调用。 例子如下:
tooltipTimerId = GlobalTimer.setTimeout(
    Tooltip.TOOLTIP_DELAY_MS,
    handleTooltipAppear,
    tootipParams
);

[...]

class GlobalTimer {
    private static var timerList:Array<Timer>;

    public static function setTimeout(milliseconds:Int, func:Dynamic, args:Array<Dynamic>=null):Int {
        var timer:Timer = new Timer(milliseconds);
        var id = addTimer(timer, timerList);
        timer.run = function() {
            Reflect.callMethod(null, func, args);
            clearTimeout(id);
        }   
        return id;
    }

    private static function addTimer(timer:Timer, arr:Array<Timer>):Int {
        for (i in 0...arr.length) {
            if (null == arr[i]) {
                arr[i] = timer;
                return i;
            }
        }
        arr.push(timer);
        return arr.length -1;
    }

    public static function clearTimeout(id:Int) {
        var timers:Array<Timer> = GlobalTimer.getInstance().timerList;
        try {
            timers[id].stop();
            timers[id] = null;
        } catch(e:Error) {/* Nothing we can do if it fails, really. */}
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接