0

i see allways that people write in the collusion function (example):

    local onCollision = function(event)
        if event.phase == "began" then
            event.object2:removeSelf();
            event.object2 = nil;
        end
end
Runtime:addEventListener("collision",onCollision);

why you dont just write:

local onCollision = function(event)
            event.object2:removeSelf();
            event.object2 = nil;
end
Runtime:addEventListener("collision",onCollision);

I dont understand what is the point?

idan ahal
  • 707
  • 8
  • 21
  • I'm almost entirely unfamiliar with corona but I would assume the collision function gets called on multiple parts of the collision and these parts are marked in `event.phase` so using your latter snippet the function will try to operate on `object2` during multiple phases and this will cause a problem during any secondary phases as it will already have been destroyed. – Etan Reisner Apr 08 '15 at 00:36

1 Answers1

0

consider this example,

local object = display.newImage( "ball.png" )

function object:touch( event )
 if event.phase == "began" then

    display.getCurrentStage():setFocus( self )
    self.isFocus = true

elseif event.phase == "moved" then

        print( "moved phase" )

elseif event.phase == "ended" or event.phase == "cancelled" then

        display.getCurrentStage():setFocus( nil )
        self.isFocus = false
    end
end

 return true
end
object:addEventListener( "touch", object )

If you doesn't add the phase your touch will be detected in all the three phase, thus it executes all the statements with in function three times.

To avoid this we are using the phase.

In your case ,

 local onCollision = function(event)
        event.object2:removeSelf();
        event.object2 = nil;
 end
 Runtime:addEventListener("collision",onCollision);

The code inside this will be called three times, this results in error. Since in began phase itself your object will be removed, when it comes to moved phase it will give you error, since object is already removed.

Please refer this, http://docs.coronalabs.com/api/event/touch/phase.html

Kumar KS
  • 521
  • 8
  • 18