2014-02-11 72 views
1

我正在从一本书中学习方向。我对代码event.type非常困惑。困惑于event.type Lua

下面是书中的代码:

portrait = display.newText ("Portrait", display.contentWidth/2,display.contentHeight/ 2, nil,20) 
portrait: setFillColor (1,1,1) 
portrait.alpha = 1 

landscape = display.newText ("Landscape", display.contentWidth/ 2, display.contentHeight /2, nil, 20) 
landscape: setFillColor (1,1,1) 
landscape.alpha = 0 

local function onOrientationChange (event) 
if (event.type == 'landscapeRight' or event.type == 'landscapeLeft') then 
    local newAngle = landscape.rotation - event.delta 
    transition.to (landscape, {time = 1500, rotation = newAngle}) 
    transition.to (portrait, {rotation = newAngle}) 
    portrait.alpha = 0 
    landscape.alpha = 1 
else 
    local newAngle = portrait.rotation - event.delta 
    transition.to (portrait, {time = 150, rotation = newAngle}) 
    transition.to (landscape, {rotation = newAngle}) 
    portrait.alpha = 1 
    landscape.alpha = 0 
end 
end 

好像整个方向改变功能工作围绕event.type。我不明白它是什么,我不明白它是什么(==)。此外,当我更改字符串(在本例中为'landscapeRight'和'landscapeLeft')时,它也是一样的。它会采取任何价值,仍然可以正常工作。我对它的工作原理感到困惑,请解释event.type。

回答

1

我希望你能接受MBlanc的回答,我只是要在这里展开Runtime对象:定向event.type是几个字符串中的一个值,指示上该链接在MBlanc的帖子中。 Event.type绝不会是这些字符串以外的任何东西。所以你通过改变比较能不会匹配event.type在“其他”分支所有的时间结束了,好像你的设备从未在景观导向字符串做:

local function onOrientationChange (event) 
    if (event.type == 'blabla1' or event.type == 'blabla2') then 
     ...do stuff -- but will never get run because event.type can never have those values 
    else -- so your program always ends up here: 
     ...do other stuff... 
    end 
end 

这将使它看起来好像程序运行良好,只是当你的设备真的处于方向landscapeRight或者离开时程序将执行“else”块而不是它应该执行的块(第一块)。

2

这是一个常见的Lua习惯用字符串'landscapeRight'作为枚举文字。

对于orientation事件,event.type保持新的设备方向。

在您提供的代码片段中,您在定义它之后似乎没有调用或以其他方式对onOrientationChange进行任何引用。你应该把它安装到使用

Runtime:addEventListener('orientation', onOrientationChange) 
+0

+1我添加了一个答案 – Schollii