Developing iPhone/iPad/Android Games with Corona: Creating Animations

In this demonstration, we will take our existing Hello World project and add some animation.

To get started, we have the existing code:

local textObj = display.newText(“Hello World!”, 50, 50, nil, 24)
textObj:setTextColor( 255, 255, 255)

local mybutton = display.newImage( “button.png” )
mybutton.x = display.contentWidth/2
mybutton.y = display.contentHeight-75

local h = textObj.height
local w = textObj.width

function mybutton:tap( event )
textObj.x = math.random(w/2, display.contentWidth – (w/2))
textObj.y = math.random(h/2, display.contentHeight -(100 + h/2))

mybutton:addEventListener( “tap”, mybutton )

This little Corona app will randomly place the text “Hello World” within the confines of the screen canvas area.

Today we are going to add the ability for the text to smoothly travel from current location to its new location that has been randomly generated.
If you are familiar with Flash, then you have probably used tweening.  In Corona, we can create similar transitions using the command object, {array} )

Within the array of the parameters, we pass what we would like to change and how quickly we want that transition to occur.

My new function (replacing the old mybutton fuction) looks like:
function mybutton:tap( event ), { time=1000, x = math.random(w/2, display.contentWidth – (w/2)),
y = math.random(h/2, display.contentHeight -(100 + h/2)) } )

In this function, I have passed the textObj object as the object.  In the array, I’m passing it a time parameter that is set to 1000 milliseconds (or 1 second), and then the x and y variables.  As you can see in the code, this is exactly the same code that we had previously, it is just set to transition the change of location over 1 second.

You can see the full demonstration here:

[tubepress video=cm_ys-M3Mng]

Note: I have changed display.stageWidth and display.stageWidth to display.contentWidth & display.contentHeight for version 2.0 of Corona.  As of 2.0 stageHeight & stageWidth have been depreciated.

Recent Posts