移动每个单独的对象 - Lua

我很新于 Lua 编程,所以请原谅我的无知,但是我找不到解决我的问题的方法。

正在发生什么

我目前正在尝试将对象从 A 移动到 B,一旦对象到达 B,就重新从 A 开始,并在连续周期中再次移动到 B

local function moveLeft(obj)
    print("moving left")
    local function resetObj(obj)
        transition.to (obj,{  time = 10, x = obj.x + screenWidth + obj.width, onComplete=moveLeft  })
    end

    transition.moveBy (obj,{  time = 3000, x = -screenWidth -obj.width, onComplete=resetObj })
end

并使用以下代码进行调用:

for idx1 = 1, 8 do
    enemyRed = display.newImage("Images/enemyRed.png")
    -- 7. Apply physics engine to the enemys, set density, friction, bounce and radius
    physics.addBody(enemyRed, "dynamic", {density=0.1, friction=0.0, bounce=0, radius=9.5});
    local xPositionEnemy = math.random() + math.random(1, screenWidth)
    enemyRed.x = xPositionEnemy;
    enemyRed.y = yPosition;
    enemyRed.name = "enemyRed"..idx
    moveLeft(enemyRed);
end

这很好,所有对象都从 AB 移动。

问题 / 问题所在

问题在于,直到所有名为 "enemyRed" 的对象都到达点 B,onComplete 才会被调用。

问题

我希望每个名为 "enemyRed" 的个体对象在到达目的地后都返回原始位置 A。

点赞
用户869951
用户869951

我无法回答这个问题/问题,因为它不清楚(我添加了一个注释)。关于问题,您可能应该向每个对象添加一个A位置字段,这样您可以轻松返回(样式注释:这是Lua,不是C,您不需要分号)。所以在您的循环中,做这个:

enemyRed.x = xPositionEnemy
enemyRed.startPos = xPositionEnemy

那么在您的 resetObj 中,做这个:

local function moveLeft(obj)
    local function resetObj()
        print("moving back")
        transition.to (obj,
            {  time = 10, x = obj.startPos, onComplete=function() moveLeft(obj) end  })
    end

    print("moving left")
    transition.moveBy (obj,
        {  time = 3000, x = -screenWidth - obj.width, onComplete=resetObj })
end

以上还表明,当从 resetObj 函数调用您的 moveLeft 时,您必须将 obj 传递给 moveLeft,否则 obj 将为零。resetObj 不需要 obj \ `参数,因为它已经是一个upvalue了。

2014-05-09 11:28:20