2014-02-11 111 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