将表格添加为事件侦听器

如何将表格添加为事件侦听器? 我正在进行一个砖块游戏作为hello-world项目,我想添加“双球”的效果。所以基本上我想要将球添加到“球表”中,然后检查是否有一个球击中了砖块。

我的代码与以下内容一起工作:

balls["ball"]:addEventListener( "collision", removeBricks )

但是如果我尝试以下内容:

balls:addEventListener( "collision", removeBricks )

我会收到Runtime error ...\main.lua:753: attempt to call method 'addEventListener' (a nil value)stack traceback:

我尝试过的内容:

local balls = {}

balls["ball"] = crackSheet:grabSprite("ball_normal.png", true)
balls["ball"].name = "ball"

    function removeBricks(event)

            if event.other.isBrick == 1 then
                remove brick...
            end
    end

balls.collision = removeBricks
balls:addEventListener( "collision", removeBricks )
点赞
用户2186639
用户2186639

你无法给表格添加事件侦听器。如果您想检查砖块与球的碰撞,则应将事件侦听器添加到每个球或每个砖块。

2013-07-03 21:55:32
用户1682268
用户1682268

你可以尝试创建每个球的实例,而不是使用表格,然后尝试在每个球上添加碰撞事件监听器,查看代码如下:

local Table = {}
local function generateBall(event)

   if "ended" == event.phase then
      local ball = crackSheet:grabSprite("ball_normal.png", true)
      ball.name = "ball"

      local function removeBricks(event)
          if "ended" == event.phase then
              if event.other.isBrick == 1 then
                remove brick...
            end
          end
      end

      ball:EventListener("collision", removeBricks)
      table.insert(Table, ball)
   end

end

Runtime:EventListener("touch",generateBall)

这样可以使每个球有不同的监听器。

2013-07-04 01:08:36
用户1605727
用户1605727

如果您想在表格中添加球,可以在表格中插入对象

local ballsTable = {}

function addBall()
    local ball = crackSheet:grabSprite("ball_normal.png", true)
    ball.name = "ball"

    ball.collision = function(self, event)
        if event.other.isBrick == 1 then
            event.other:removeSelf()
        end
    end
    ball:addEventListener( "collision" )

    table.insert(ballsTable, ball)
end
2013-07-04 04:06:40