Developing for iPhone/iPad/Android with Corona: Fade in and Fade out


This tutorial will provide the basics of doing a simple object fade in and fade out using the alpha.

Alpha is commonly used in game environments to cause objects to be not visible or only partially visible.  At zero, an object is invisible, at one (or 100%), an object is fully visible.

To get started, we will use the code we finished with when we created our interactive Hello World project:

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))
end

mybutton:addEventListener( “tap”, mybutton )

We just need to add two lines to the mybutton function:
textObj.alpha =0
before changing the objects x and y, and
transition.to (textObj, {time=3000, alpha=1})
just before our ‘end’

When you run the new code, the text will disappear, then fade in at its new location.  The final function should look like this:
function mybutton:tap( event )
textObj.alpha =0
textObj.x = math.random(w/2, display.contentWidth – (w/2))
textObj.y = math.random(h/2, display.contentHeight -(100 + h/2))
transition.to (textObj, {time=3000, alpha=1})
end


Note: If you cut and past the above code into your editor of choice, you will need to replace the quotes with system quotes, else it will generate an error.

Demonstration:
[tubepress video =AFr9dwZ6Ly8 ]

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