I have a question I haven’t been able to figure out by reading the forums, documentation, and looking through sample code. Let’s say I want a function to create an object (like a game character). I expect to create a lot of these. I’ve seen it done this way:
[lua]function createCharacter(params)
local myCharacter = display.newImage(“character.png”)
– create the character, add physics, set status, insert in groups, etc.
function myCharacter:touch(event) – for some reason this gives an error when it’s local. Maybe it’s destroyed when function ends?
– handle touch event, there could be a lot in here, calling other functions, etc.
return true
end
function myCharacter:collision(event)
– handle collision event, there could be a lot in here, calling other functions, etc.
return true
end
myCharacter:addEventListener( “touch”, myCharacter )
myCharacter:addEventListener( “collision”, myCharacter )
return myCharacter
end[/lua]
But this gets messy, because my touch and collision event handlers are long and complex. And does this create a different copy of the collision and touch handlers every time I call createCharacter?
If I put the touch and collision event handlers outside the function like this:
[lua]local function myCharacterTouchHandler(self,event)
– handle touch event, there could be a lot in here, calling other functions, etc.
return true
end
local function myCharacterCollisionHandler(self,event)
– handle collision event, there could be a lot in here, calling other functions, etc.
return true
end
function createCharacter(params)
local myCharacter = display.newImage(“character.png”)
– add physics, set status, insert in groups, etc.
myCharacter.touch = myCharacterTouchHandler
myCharacter:addEventListener( “touch”, myCharacterTouchHandler )
– I notice this also works: myCharacter:addEventListener( “touch”, myCharacter )
myCharacter.collision = myCharacterCollisionHandler
myCharacter:addEventListener( “collision”, myCharacterCollisionHandler)
return myCharacter
end[/lua]
Is the second way the “right” way to handle this, when you’re running the createCharacter multiple times?
[import]uid: 49372 topic_id: 9162 reply_id: 309162[/import]