2013-07-03 79 views
1

如何将表添加为EventListener? 我正在做一个突击游戏作为hello-world项目,我想添加“双重球”的效果。所以基本上我想球添加到balls table然后检查一个球撞砖将表添加为EventListener

我的代码与

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

,但如果我尝试以下方法:

balls:addEventListener("collision", removeBricks) 

我” m到处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) 

回答

2

您不能将事件侦听器添加到表中。如果你想检查砖与球碰撞,你应该添加事件监听器到每一个球或每一块砖

1

你可以尝试创建一个球的每个实例,而不是使用表,然后尝试添加碰撞eventlistener每次球看代码

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) 

这样你可以在每一个球

0

有不同的听众如果你想添加的球在你的表,你可以在表中插入对象

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 
相关问题