Corona/Lua 和碰撞:尝试连接字段'name'(一个空值)。

我在尝试让碰撞检测起作用,但似乎无法找到问题所在。

我收到的错误是:

'...\main.lua:178:尝试连接字段'name'(一个空值)'

我的情况是这样的:我有一个盒子(“飞船”),它保持固定的X坐标,但上下移动。它要通过由两个矩形构成的“隧道”,并且我试图检测飞船与隧道的墙壁之间的碰撞(即矩形)。

当碰撞发生时,我得到这个错误。我的大部分代码只是官方Corona文档的修改版本,我无法弄清问题出在哪里。

下面是相关的代码片段:

function playGame()
    -- 显示飞船
    ship = display.newRect(ship);
    shipLayer:insert(ship);
    -- 为飞船添加物理效果
    physics.addBody(ship, {density = 3, bounce = 0.3});

    ...

    beginRun();
end

function beginRun()
    ...
    spawnTunnel(1100); -- 这只是在特定位置调用createTunnel函数
    gameListeners("add");
    ...
end

function gameListeners(event)
    if event == "add" then
        ship.collision = onCollision;
        ship:addEventListener("collision", ship);
        -- 对顶部重复上述两行代码
        -- 对底部重复上述两行代码
    end
end

-- 碰撞处理程序
function onCollision(self,event)
    if ( event.phase == "began" ) then
        -- 第178行代码正好在此行下面 -----------------------------------------
        print( self.name .. ": collision began with " .. event.other.name )
end

-- 使用2个矩形创建“隧道”
function createTunnel(center, xLoc)
    -- 创建顶部和底部矩形,都命名为“box”
    top = display.newRect(stuff);
    top.name = "wall";
    bottom = display.newRect(stuff);
    bottom.name = "wall";

    -- 将它们添加到middleLayer组中
    middleLayer:insert(top);
    middleLayer:insert(bottom);

    -- 将物理效果添加到矩形上
    physics.addBody(top, "static", {bounce = 0.3});
    physics.addBody(bottom, "static", {bounce = 0.3});
end

只有当两个对象应该发生碰撞时才会收到错误消息,因此看起来碰撞正在发生且正在被检测到。但由于某种原因,self.name和event.other.name却为空。

点赞
用户3171803
用户3171803

尝试使用:

top.name = "wall";

bottom.name = "wall";

作为

top.myName = "wall"

bottom.myName = "wall";

在你的 "createTunnel: function 后面使用 onCollision 函数:

-- 碰撞处理程序
function onCollision( self, event)

    if ( event.phase == "began" ) then
        print( self.myName .. ": collision began with " .. event.other.myName )
    end
end
2014-02-14 13:07:14
用户2870859
用户2870859

哇哦。花费了许多时间后,我终于发现了自己愚蠢却简单的错误。问题在于我忘记给飞船命名了。现在代码看起来像这样,而且也可以正常工作:

function playGame()
    -- 显示飞船
    ship = display.newRect(ship);
    ship.name = "ship";  -- 添加此行以给飞船命名
    shipLayer:insert(ship);
    -- 给飞船添加物理特性
    physics.addBody(ship, {density = 3, bounce = 0.3});

    ...

    beginRun();
end
2014-02-15 05:36:18