Tom
Tom

Reputation: 2418

move each individual object - lua

Im quite new to Lua so please pardon my ignorance but i cannot find the solution to my problem.

Whats going on

Im currently trying to move objects from A to B and once object is at B to restart at A and again move to B in a continuous cycle.

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

and then called using

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

This is great and all objects are moving from A to B

Problem / issue

The issue here is that the onComplete is not called until ALL objects named "enemyRed" are at point B.

Question

What i want is for each individual object named "enemyRed" to reset to original position A once its reached its destination.

Upvotes: 0

Views: 182

Answers (1)

Oliver
Oliver

Reputation: 29523

I can't answer the problem/issue because it is not clear (I added a comment). Re the question, you should probably add a A position field to each object, this way you can easily return to it (stylistic note: this is Lua, not c, you don't need semicolons). So In your loop do this:

enemyRed.x = xPositionEnemy
enemyRed.startPos = xPositionEnemy

then in your resetObj do this:

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

The above also shows that when calling your moveLeft from the resetObj function, you have to give the obj to the moveLeft otherwise obj will be nil. The resetObjdoes not needobj` parameter since it is an upvalue already.

Upvotes: 1

Related Questions