Sorry for bumping an old thread!
In my current project I had to know when an orientation really changed (or just flipped by 180°) so that I could decide when and how to reposition and rerender some objects.
I noticed that orientationChanged is fired multiple times and that was not wat I expected from this function. It was also difficult to track and compare current and old WIDTH,HEIGHT values of the screen. So I rewrote Codea’s implementation of the orientationChanged() callback. For anyone who encounter the same issues here is my code:
do
local _orientationChanged = orientationChanged or function() end
local portrait = table.concat({PORTRAIT, PORTRAIT_UPSIDE_DOWN, PORTRAIT_ANY}, ",")
local landscape = table.concat({LANDSCAPE_LEFT, LANDSCAPE_RIGHT, LANDSCAPE_ANY}, ",")
local prevOrientation = CurrentOrientation
local prevWidth = WIDTH
local prevHeight = HEIGHT
local function name(orientation)
if portrait:find(orientation) then
return "PORTRAIT"
else
return "LANDSCAPE"
end
end
local function screen()
return {
prevOrientation = prevOrientation,
currOrientation = CurrentOrientation,
prevOrientationName = name(prevOrientation),
currOrientationName = name(CurrentOrientation),
prevWidth = prevWidth,
currWidth = WIDTH,
prevHeight = prevHeight,
currHeight = HEIGHT
}
end
function orientationChanged()
if prevWidth ~= WIDTH or prevHeight ~= HEIGHT then -- device rotated 90°
_orientationChanged(screen())
prevOrientation = CurrentOrientation
prevWidth = WIDTH
prevHeight = HEIGHT
elseif prevOrientation ~= CurrentOrientation then
if (landscape:find(CurrentOrientation) and landscape:find(prevOrientation)) -- device rotated 180°
or (portrait:find(CurrentOrientation) and portrait:find(prevOrientation))
then
_orientationChanged(screen())
prevOrientation = CurrentOrientation
end
end
end
end
Put this code into a separate tab and move that tab to the right of the “Main” tab, so that it overrides Codea’s original call to orientationChanged. Then use orientationChanged(screen)
as before, but now screen variable is a table of values that you can use for better control.
Use like this:
function orientationChanged(screen)
print(string.format(
"Orientation changed from %d (%s) to %d (%s)",
screen.prevOrientation,
screen.prevOrientationName,
screen.currOrientation,
screen.currOrientationName
))
if screen.prevOrientationName == screen.currOrientationName then
print("Device was rotated 180°")
print("Screen dimensions didn't change")
else
print("Device was rotated 90°")
print(string.format(
"Screen dimensions changed from (%d,%d) to (%d,%d)",
screen.prevWidth,
screen.prevHeight,
screen.currWidth,
screen.currHeight
))
end
end