@henriquesv,
I’m not aware of any existing libraries for Corona that implement a behavior- or component- based approach.
That said I’m glad you’re asking this question. I’ve been considering implementing a component.* plugin and a community accessible library of components, but I wasn’t sure if the community would dig it or not.
For now, until I make up my mind and then get done with the initial version of this, you have to code this kind of thing on your own.
My own approach to this kind of coding it to use custom events as follows:
First, a basic KEY listener to catch WASD events and throw custom events (just as an example).
local function key( event ) if( event.phase == "down" ) then -- the key press if(event.keyName == "w" ) then Runtime:dispatchEvent( { name = "onMove", y = -1, phase == "began" } ) elseif(event.keyName == "a" ) then Runtime:dispatchEvent( { name = "onMove", x = -1, phase == "began" } ) ... more ... elseif( event.phase == "up" ) then -- the key release if(event.keyName == "w" ) then Runtime:dispatchEvent( { name = "onMove", y = 1, phase == "ended" } ) elseif(event.keyName == "a" ) then Runtime:dispatchEvent( { name = "onMove", x = 1, phase == "began" } ) ... more ... end
Then, an object with a listener for the custom event ‘onMove’
local player = display.newCircle( 10, 10, 10 ) player.moveX = 0 player.moveY = 0 function player.onMove( self, event ) self.moveX = self.moveX + (event.x or 0) self.moveY = self.moveY + (event.y or 0) end; Runtime:addEventListener( "onMove", player ) function player.enterFrame( self ) self.x = self.x + self.moveX self.y = self.y + self.moveY end; Runtime:addEventListener( "enterFrame", player )
This may all seem a bit convoluted at first, and some may say… why not just attach the key listener directly to the player.
While you could do that, if you should later decide to change from a key-input to a touch input or a joystick input, you’d have to recode the movement logic. If however, you separate the input from the processing, you can simply add a new input listener and Viola, you’re good go go!
Finally, the above example sucks! I know, but I just wanted to demonstrate some principles while answering your question.