在使用Storyboard库恢复场景后,在onCollision中event.other为nil [CORONA SDK]。

我在使用 Corona SDK 开发时遇到了一个与碰撞检测和故事板库有关的奇怪错误。

这是我的onCollision侦听器:

local function onBottomBorderCollision( event )
    if (event.other.isBall) then
        local index = table.indexOf( ballArray, other )
        table.remove( ballArray, index )
        event.other:removeSelf( )
        event.other = nil
        updateLife(false)
        updateScore(false)
    end
end

这在首次启动时完美运行,但在返回菜单屏幕(使用storyboard.goToScene(“menu”))并重新播放游戏后,现在每当我的球撞到底部边界时,此侦听器将触发以下错误:

尝试索引字段“ other”(一个nil值)

我确实在scene:onEnterScene(scene)中创建了适当的侦听器,所以这不是它们的问题,而且这个其他侦听器从未生成过错误:

local function onPlayerCollision( event )

    if(event.other.isBall) then
       xVel, yVel = event.other:getLinearVelocity( )
       event.other:setLinearVelocity( event.other.XLinearVelocity, yVel )

   end

end

我现在卡住了...请帮忙!

点赞
用户2260388
用户2260388

我认为问题是因为当你切换场景时,故事板会在内存中保存一些变量。 显示对象被销毁,但引用仍然存在。 你可能正在CreateScene函数中初始化你的显示对象,如果你不移除场景,CreateScene函数只会被调用一次。

在菜单的enter scene函数中销毁场景可能会解决问题。这可以通过Storyboard.removeScene函数完成。

在menu.lua的"EnterScene"函数中,添加一行以删除场景。 例如,如果你的场景名为game:

storyboard.removeScene("game")

你可以在这里了解有关destroyScene和purgeScene之间的区别。

2014-06-01 08:47:59
用户1979583
用户1979583

实际上,这种错误主要是由于一些活动函数调用/定时器/转换,未在更改场景之前取消,导致的。

尝试索引字段“other”(值为nil

上面的错误提到正在调用/获取任何对象/其属性,但它不在当前发生或场景中。因此,请检查您是否取消了定时器,转换和运行时事件侦听器。


在您的情况下,可能是运行时未取消碰撞检测函数 onBottomBorderCollision 导致的故障。如果您在 enterFrame 中调用它,则必须在场景更改之前将其取消。您可以按如下方式执行:

Runtime:removeEventListener("enterFrame", onBottomBorderCollision)

更新: 在运行碰撞检查时无法停止物理引擎。因此,请按照以下步骤操作:

function actualSceneChange()
     physics.stop() -- 在此处停止物理
     -- 调用场景更改
     director:changeScene("menuPageName") -- 调用您的场景更改方法
end

function initiatingSceneChange()
    physics.pause() -- 此处暂停物理引擎
    -- 停止不需要的事件侦听器
    Runtime:removeEventListener("enterFrame", onBottomBorderCollision)

    if(timer_1) then timer.cancel(timer_1) end    -- 像此类停止所有计时器。
    if(trans_1) then transition.cancel(trans) end -- 像此类停止所有转换。

    timer.performWithDelay(1000, actualSceneChange, 1)
end
2014-06-12 07:15:43