Reputation: 169
How can I add tables as a EventListener?
I'm working on a breakout game as a hello-world project and i would like to add the effect of "double ball". so basically i want to add balls to balls table
then check if one of the balls hit the brick
my code works with
balls["ball"]:addEventListener( "collision", removeBricks )
but if i try the following:
balls:addEventListener( "collision", removeBricks )
i'm getting Runtime error ...\main.lua:753: attempt to call method 'addEventListener' (a nil value)
stack traceback:
what i've tried:
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 )
Upvotes: 1
Views: 104
Reputation: 1616
you can try creating each instance of a ball instead of using a table and then try to add collision eventlistener on every ball try to look at the code
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)
this way you can have different listener on every ball
Upvotes: 1
Reputation: 4007
If you want to add balls in your table you can insert objects in table
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
Upvotes: 0
Reputation: 3982
You can't add event listener to a table. If you want to check bricks vs. ball collisions you should add event listeners to every ball or every brick
Upvotes: 2