Get touch event on a table of rectangle objects

I am a corona beginner, I have a grid of rectangle objects and i will like to get touch event on any of them when touched. The problem is that i don’t know how to add touch event on individual rectangle objects because they are being generated in a for loop. Please I will appreciate any form of advice, including references, thanks. 

Hi @martinsdennis86,

Adding touch events to objects in a “for” loop is basically the same as adding a touch listener to any one object. In the loop, just add the touch listener, and make its listener function as a function scoped somewhere above. Like this:

[lua]

local function touchMe( event )

   print( event.phase )

   print( event.target )

end

for i = 1,10 do

   local rect = display.newRect( 0, 0, 50, 50 )

   – position the rectangle where you need it

   rect:addEventListener( “touch”, touchMe )

end

[/lua]

Hope this helps,

Brent

Thanks Brent, it helped and i really do appreciate.

And now development in progress…

Hi @martinsdennis86,

Adding touch events to objects in a “for” loop is basically the same as adding a touch listener to any one object. In the loop, just add the touch listener, and make its listener function as a function scoped somewhere above. Like this:

[lua]

local function touchMe( event )

   print( event.phase )

   print( event.target )

end

for i = 1,10 do

   local rect = display.newRect( 0, 0, 50, 50 )

   – position the rectangle where you need it

   rect:addEventListener( “touch”, touchMe )

end

[/lua]

Hope this helps,

Brent

Thanks Brent, it helped and i really do appreciate.

And now development in progress…