Corona / Lua和碰撞:“尝试连接字段'名称'(零值)”

时间:2014-02-14 12:32:03

标签: android ios lua corona collision

我正在尝试进行一些碰撞检测,但我似乎无法弄清楚问题是什么。

我得到的错误是

...\main.lua:178:attempt to concatenate field 'name' (a nil value)

我所拥有的是:我有一个盒子(“船”),它停留在固定的X坐标上,但是上下移动。它意味着经过一个由两个矩形组成的“隧道”,它们之间有一个间隙,我试图探测船与隧道墙壁之间的碰撞(即矩形)。

碰撞发生时我收到此错误。我的很多代码只是官方Corona文档的修改版本,我只是无法弄清问题是什么。

以下是相关的代码:

function playGame()
    -- Display the ship
    ship = display.newRect(ship);
    shipLayer:insert(ship);
    -- Add physics to ship
    physics.addBody(ship, {density = 3, bounce = 0.3});

    ...

    beginRun();
end

function beginRun()
    ...
    spawnTunnel(1100); -- this just calls the createTunnel function at a specific location
    gameListeners("add");
    ...
end

function gameListeners(event)
    if event == "add" then
        ship.collision = onCollision;
        ship:addEventListener("collision", ship);
        -- repeat above two lines for top
        -- and again for bottom
    end
end

-- Collision handler
function onCollision(self,event)  
    if ( event.phase == "began" ) then
        -- line 178 is right below this line  ----------------------------------
        print( self.name .. ": collision began with " .. event.other.name )
end

-- Create a "tunnel" using 2 rectangles
function createTunnel(center, xLoc)
    -- Create top and bottom rectangles, both named "box"
    top = display.newRect(stuff);
    top.name = "wall";
    bottom = display.newRect(stuff);
    bottom.name = "wall";

    -- Add them to the middleLayer group
    middleLayer:insert(top);
    middleLayer:insert(bottom);

    -- Add physics to the rectangles
    physics.addBody(top, "static", {bounce = 0.3});
    physics.addBody(bottom, "static", {bounce = 0.3});
end  

一旦两个对象发生碰撞,我才会收到错误消息,因此看起来碰撞正在发生,并且正在检测到它。但由于某种原因,self.name和event.other.name为nil。

2 个答案:

答案 0 :(得分:0)

尝试使用:

top.name = "wall";

bottom.name = "wall";

作为

top.myName = "wall"

bottom.myName = "wall";

在“createTunnel:function:

”之后使用onCollision函数
-- Collision handler
function onCollision( self, event)

    if ( event.phase == "began" ) then
        print( self.myName .. ": collision began with " .. event.other.myName )
    end
end

答案 1 :(得分:0)

哇,哇。几个小时后,我终于找到了我的愚蠢而简单的错误。

问题是我忘了给船上自己的名字。代码现在看起来像这样,工作得很好:

function playGame()
    -- Display the ship
    ship = display.newRect(ship);
    ship.name = "ship";  -- added this line to give the ship a name
    shipLayer:insert(ship);
    -- Add physics to ship
    physics.addBody(ship, {density = 3, bounce = 0.3});

    ...

    beginRun();
end