Ashkan
Ashkan

Reputation: 345

How to create, move and remove dynamic objects in corona sdk?

I recently started programming with corona sdk to make a simple game. I need to create dynamic objects and when I move some object out it removes itself. I can create dynamic objects but I can't handle the events on each one.

I want to do it all by functions.

Here's a piece of my code and in last function (myObject:touch) I'd like to change it to a new function which will handle all objects not only myObject so I need to send object name as a parameter to that function. Would you please help?

function create_obj(img,xpos,ypos)  
    myObject = display.newImage(img)
    myObject.x=xpos
    myObject.y=ypos
end

function move_out(obj)
    transition.to( obj, { time=2000, alpha=1, x=60, y=60, width=1 ,height=1, onComplete= remove_obj(obj) } )
end

function remove_obj(obj)    
    obj:removeSelf()
    obj=nil
end

--create 1st object
local img1="icon1.png"
create_obj(img1,50,50)

--create 2nd object
local img2="icon2.png"
create_obj(img2,100,100)

--create 3rd object
local img3="icon3.png"
create_obj(img3,150,150)

function myObject:touch( event )
    if event.phase == "began" then
        self.markX = self.x -- store x location of object
        self.markY = self.y -- store y location of object
    elseif event.phase == "moved" then
        local x = (event.x - event.xStart) + self.markX
        local y = (event.y - event.yStart) + self.markY
        self.x, self.y = x, y 
    elseif event.phase == "ended" or event.phase == "cancelled" then
        move_out(myObject)
    end
    return true 
end


   myObject:addEventListener( "touch", myObject )

Upvotes: 0

Views: 766

Answers (1)

Teddy Engel
Teddy Engel

Reputation: 1006

I think what you are looking for here is simply to change the transition in moveOut like this:

function move_out(obj)
    transition.to( obj, { time=2000, alpha=1, x=60, y=60, width=1 ,height=1, onComplete=function() remove_obj(obj) end } )
end

Upvotes: 2

Related Questions