Developing iPhone/iPad/Android applications with Corona: Orientation Change


In this final “Hello World” with Corona, we will look at how to allow for orientation change in our app.

First, please recognize that this is for a general rotation.  Seldom will this be sufficient to handle all rotation needs of your app.  You will usually need to code in the screen size and where you want the object to be located in the new orientation.

I’m going to start with the code that we used for adding sound effects to our app:

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 )
media.playEventSound(“beep.caf”)
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

mybutton:addEventListener( “tap”, mybutton )

To handle orientation, we will need to add a new listener and a function to handle the orientation change:
local function onOrientationChange (event)
local newAngle = textObj.rotation – event.delta
transition.to( textObj, {time= 150, rotation = newAngle})
end

Runtime:addEventListener( “orientation”, onOrientationChange )

The Runtime:addEventListener looks for the orientation change and calls the function.  The function looks at the current angle of textObj and calculates the new orientation angle by subtracting the event.delta.  After calculating the new angle, we perform a transition to the new orientation.  Our final code looks like:

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 )
media.playEventSound(“beep.caf”)
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

local function onOrientationChange (event)
local newAngle = textObj.rotation – event.delta
transition.to( textObj, {time= 150, rotation = newAngle})
end

mybutton:addEventListener( “tap”, mybutton )
Runtime:addEventListener( “orientation”, onOrientationChange )

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.


Demonstration:
[tubepress video = BVS5AMI-Ab0]

Recent Posts