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

Posted by Dr. Burton on July 9, 2010 in Android, Corona, iPad, iPhone, Mobile |

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:

Andorid/iPhone game development with Corona: Fade In and Out
Runtime
2:33
View count
1,771

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.

2 Comments

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree

Copyright © 2010-2012 Burtons Media Group All rights reserved.
Desk Mess Mirrored version 1.9.1 theme from BuyNowShop.com.