0

我总是看到人们在勾结函数中写(示例):

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

为什么你不只是写:

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

我不明白这是什么意思?

4

1 回答 1

0

考虑这个例子,

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 )

如果您不添加阶段,您的触摸将在所有三个阶段中检测到,因此它将执行所有带有 in 函数的语句三次。

为了避免这种情况,我们使用了相位。

在你的情况下,

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

this里面的代码会被调用3次,导致报错。由于在开始阶段本身您的对象将被删除,当涉及到移动阶段时,它会给您错误,因为对象已经被删除。

请参考这个,http://docs.coronalabs.com/api/event/touch/phase.html

于 2015-04-08T06:28:02.810 回答