2013-07-03 30 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 
相關問題