如何使用带有方法调用的timer.performWithDelay

我正在使用Lua类创建两个对象,每个对象必须检查另一个对象的位置以确定它们的移动。我试图使用timer.performWithDelay使它们每秒钟检查一次,但是当我尝试这样做时,类构造函数中的

o.moveCheckTimer = timer.performWithDelay(1000, o:moveCheck, 0)

会抛出一个错误,指出“函数参数在','附近期望”。

我尝试使用匿名函数,如下所示:

o.moveCheckTimer = timer.performWithDelay(1000, function() o:moveCheck() end, 0)

但是,这会导致两个对象的计时器只调用最近创建的对象的函数,而不是自身的函数(这也是非常令人困惑的行为,如果有人知道这是为什么,我很想了解为什么)。

我已经彻底查看了API和关于方法调用的信息,但似乎找不到两者共同使用的内容,我觉得我漏掉了什么。

我如何使用方法调用作为此定时器的侦听器?

下面是完整的构造函数:

Melee = {}
Melee.__index = Melee

function Melee:new(id, name, lane, side)
    local o = {}
    setmetatable(o, Melee)
    o.id = id
    o.name = name
    o.lane = lane
    o.side = side
    if name == "spearman" then
        o.maxhp = 100
        o.range = 1
        o.damage = {10, 20}
        o.imageName = "images/rebels/spearman.png"
    else
        error("尝试创建未定义名称的近战单位")
    end
    o.hp = o.maxhp
    --显示自己
    o.image = display.newImageRect(mainGroup,“images/rebels/spearman.png”,80,80)
    o.image.x = 0
    o.image.y = lanes[lane]
    o.image.anchorY = 1
    if side == 2 then
        o.image.xScale = -1
        o.image:setFillColor(0.8)
        o.image.x = display.contentWidth - 100
    end
    --移动和攻击
    local destination = display.contentWidth
    if side == 2 then
        destination = 0
    end
    o.moving = 1
    o.movement = transition.to(o.image,{x = destination,time = 30000+math.random(-200,200)})
    o.moveCheckTimer = timer.performWithDelay(1000, o:moveCheck, 0)
    --o.attackTimer = timer.performWithDelay(1000, self:attack, 0)
    return o
end
点赞