【问题标题】:why eveyone do if event.phase == "began" then...?为什么每个人都这样做 if event.phase == "begin" then...?
【发布时间】:2015-06-12 18:27:20
【问题描述】:

我总是看到人们在合谋函数中写的(示例):

    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);

我不明白这是什么意思?

【问题讨论】:

  • 我对电晕几乎完全不熟悉,但我认为碰撞函数在碰撞的多个部分被调用,这些部分在event.phase 中标记,所以使用你的后一个 sn-p 函数将尝试在多个阶段对object2 进行操作,这将在任何第二阶段导致问题,因为它已经被销毁了。

标签: lua coronasdk collision phase


【解决方案1】:

考虑这个例子,

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 函数的语句 3 次。

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

在你的情况下,

 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

【讨论】:

  • 但我现在正在使用它,它不会产生问题。
  • 请有人回答
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2017-12-08
相关资源
最近更新 更多