Corona SDK在创建行时出错。

我不明白为什么会出现以下错误: 行:107 Bad argument #1 to 'newLine' (number expected, got nil) 我想在两个触摸对象之间创建一条线。

这是我的代码:

function createstar()
    ie = ie - 300
    astar = display.newImage('ls.png', math.random( 1, 10) * 33, ie)
    astar:addEventListener( "touch", star)

    physics.addBody(astar)
    stars:insert(astar)

    sceneGroup:insert(stars)
end

function update(e)
    if(stars ~= nil)then
        for i = 1, stars.numChildren do
            stars[i].y = stars[i].y + 3
        end
     end
end

function star:touch( event )
    if event.phase == "began" then

        -- 将触摸的星星插入数组中
        table.insert(touchedStarArray, self)

        -- 检查数组中是否已经有2个星星
        if table.getn(touchedStarArray) >= 2 then

           -- 如果已经有了,那么在这两个星星之间绘制一条线
           line = display.newLine( touchedStarArray[1].x, touchedStarArray[1].y, touchedStarArray[2].x, touchedStarArray[1].y)

           -- 然后清空数组
           touchedStarArray = {}
        end
    end
end

感谢您的帮助,非常感激!

点赞
用户1870706
用户1870706

我会添加一些打印语句,并确保 touchedStarArray[1] 真的有 .x 属性。

2014-08-12 02:50:15
用户2424993
用户2424993

我假设从您粘贴的代码中可以看出,您有一个表监听器,它与每个星星创建的对象不是同一个对象。

问题在于这行代码

table.insert(touchedStarArray, self)

有两种解决方法。

一种非常简单的方法是将event.target而不是self放入touchedStarArray中(self是星星的表而不是您在createstar函数中创建的星星对象)。

table.insert(touchedStarArray, event.target)

另一种解决方法是将监听器放入star creation函数中

    function createstar()
    ie = ie - 300
    astar = display.newImage('ls.png', math.random( 1, 10) * 33, ie)
    astar:addEventListener( "touch", astar)

    function astar:touch( event )
        if event.phase == "began" then

            -- Insert touched star into array
            table.insert(touchedStarArray, self)

            -- Check if array holds 2 stars yet
            if table.getn(touchedStarArray) >= 2 then

               -- if it does then draw a line between the 2 stars
               line = display.newLine( touchedStarArray[1].x, touchedStarArray[1].y, touchedStarArray[2].x, touchedStarArray[1].y)

               -- and empty array
               touchedStarArray = {}
            end
        end
    end

    physics.addBody(astar)
    stars:insert(astar)

    sceneGroup:insert(stars)
end
2014-08-12 08:16:54