Today, I saw a question by Max N. over on “Stack Overflow”. His question was “How can I spawn the same image multiple times with individual touch handlers?”
If I understand Max’s question correctly, he basically wants to do the following:
- Create multiple images.
- Write a single touch handler.
- Get each image to use the same touch handler.
- Have the touch handler delete the object it is associated with when the object is touched.
Furthermore, Max states he is having a problem, where his handler is deleting the ‘last created’ object, not the one that was touched. Unfortunately, Max hasn’t shared his code so I have to guess at what he’s done. However, I think he probably did something like this:
local tmp = display.newCircle( 10, 10, 20 ) local function onTouch( event ) display.remove( tmp ) end tmp:addEventListener( "touch", onTouch )
If you examine the above code, you will see that the touch listener is of the function variety, and that it removes ‘tmp’, not the target of the touch.
We can fix this code in two ways:
Fix #1 – Function Listener
local tmp = display.newCircle( 10, 10, 20 ) local function onTouch( event ) display.remove( event.target ) end tmp:addEventListener( "touch", onTouch )
Now notice, the code is removing ‘event.target’, which is the object that was touched. However, this solution isn’t that great since it infers that we will create one function per object. This will soon waste a lot of memory.
Fix #2 – Single Table Listener
local function onTouch( self , event ) display.remove( self ) return true end local function createPopper( x, y ) local tmp = display.newCircle( x, y, 20 ) tmp.touch = onTouch tmp:addEventListener( "touch" ) end createPopper( 10, 10 ) createPopper( 40, 40 ) -- ... etc.
In the above example, I have written a single (table) listener and then re-used it over an over in an object builder function. Also notice, that this listener is aware of the object it is attached to. A reference to this object is automatically passed to the listener in the argument ‘self’.
Balloon Popper Sample
Just for fun, I made a simple balloon popper app to show the proper way to set up a touch listener for removing objects. Note this isn’t a full game, just an example of some basic interactive and physical mechanics. You can get it here.