반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

Corona SDK 프로그래밍 테크닉 2

2011. 11. 9. 00:01 | Posted by 솔웅


반응형
루아(Lua)에서 로컬 변수의 중요성

루아에서 가장 일반적으로 추천되는 것이 로컬화를 하라 입니다. 각각의 코드 블럭에 있는 변수를 로컬로 선언하는 것입니다. 퍼포먼스를 향상시키기 위해 아주 중요한 사항 입니다.
    myFirstName = "John"        -- global variable
    local myLastName = "Doe"    -- local variable

위 보기와 같이 변수 선언 할 때 앞에 local을 쓰면 로컬 변수이고 아무것도 쓰지 않으면 글로벌 변수 입니다.

아래 코드를 보세요.

  local myTable = { 1, 2, 3, 4, 5 }

    local printThird = function()
        print( myTable[1], myTable[2], myTable[3] )
    end

위 코드에서 myTable은 로컬입니다.
아래 코드는 이 코드와 무엇이 다를까요?

  local myTable = { 1, 2, 3, 4, 5 }

    local printThird = function()
        local t = myTable

        print( t[1], t[2], t[3] )
    end

함수 printThird 한에 t라는 로컬 변수를 선언하고 이 함수 밖의 로컬 변수인 myTable을 이 함수 안의 로컬 변수에 대입했습니다.
이것만 봐서는 크게 잇점은 없어 보입니다만 실제 앱 전체적으로는 긍정적인 효과를 줄 수 있습니다.

아래 코드를 보세요.

-- localize math function
    local mRandom = math.random

    local newObject = function()

        local obj = display.newImage( "endinggreen.png" )

        -- listener function
        function obj:enterFrame()

            -- speed up access to (already local) mRandom function
            local mRandom = mRandom

            -- do stuff...
            local rand1 = mRandom( 1, 10 )
            local rand2 = mRandom( 1, 10 )
            local rand3 = mRandom( 1, 10 )

            print( rand1, rand2, rand3 )
        end

        -- start the listener
        Runtime:addEventListener( "enterFrame", obj )

        return obj
    end

newObject();

이 코드는 rand1,rand2,rand3 의 세 랜덤 값들을 프레임마다 계속 터미널에 찍어 줍니다.



함수 밖에 local mRandom을 선언해 놓고 함수 안에서(두 번째 depth의 함수) local mRandom을 새로 만들고 이 변수에 함수 밖의 mRandom을 대입했죠? 사실 함수 안의 local mRandom = mRandom 부분을 없애도 프로그램은 제대로 돌아갈 겁니다.
하지만 이렇게 함수 안에서 다시 로컬로 변수를 선언하게 되면 퍼포먼스에 긍정적인 효과를 줍니다.
이런식으로 로컬 변수를 활용하는 습관을 들이면 프로그램 하실 때 많은 도움을 줄 겁니다.


Forward Referencing

항상 모든 것을 로컬 변수로 사용하는 것은 때로는 어려울 수 있습니다. 이럴 때 forward referencing 방법을 쓰시면 도움이 될 겁니다.

아래 코드를 보세요.

예제 1 에러코드
  local myFunction = function()
        callback()  -- ERROR: function 'callback' does not exist yet
    end

    local callback()
        print( "Hello World" )
    end

    myFunction()    -- will produce error (see above)

위 코드에서 myFunction안에서 callback()을 부를 때는 이 callback()함수가 존재하지 않습니다.
그렇기 때문에 에러가 날 겁니다.

예제 2 forward Referencing 사용한 코드

    local callback    -- forward reference (for later use)

    local myFunction = function()
        callback()    -- output: "Hello World"
    end

    -- function below is still local, because of forward reference
    callback = function()
        print( "Hello World" )
    end

    myFunction()    -- no error; happy code :-)

위 코드에서는 callback변수를 myFunction 이전에 로컬로 선언합니다.
그러면 myFunction에서 callback()함수를 호출 했을 때 이 변수를 따라가서 아래에 있는 callback()함수를 사용합니다.
이렇게 미리 변수만 로컬로 선언해 놓는 것을 forward reference라고 합니다.


Copies vs. Direct References

그럼 이 로컬 변수는 실제 선언된 값의 카피를 가지고 있는지 point를 해서 direct Reference를 하고 있는지 의문이 값니다.
정답은 루아에서는 경우에 따라 다릅니다.
테이블을 로컬화 시켰다면 이것은 실제 테이블을 direct reference 할 것입니다. 그 외에 단순히 숫자나 문자, 함수 등이라면 이것은 copy개념으로 이해하셔야 합니다.

    local myTable = { key1 = "original" }

    local testFunc = function()
        local t = myTable

        t.key1 = "modified"
    end

    testFunc()

    print( myTable.key1 )   -- output: modified

위의 코드에서 myTable은 실제 테이블의 reference를 사용합니다. 그러므로 testFunc()함수 안의 로컬 변수 t를 이용해서 값을 수정하면 실제 table의 값도 수정됩니다.



반대로 copy개념인 다른 숫자나 문자나 함수등은 이 경우 원래 함수의 값이 수정 되지는 않겠죠?

    local myNumber = 1
    local myString = 1
    local myFunction = function() print( "Hello World!" ); end

    local testFunc = function()
        local n = myNumber
        local s = myString
        local f = myFunction

        n = 2
        s = "2"
        f = nil
    end

    testFunc()

    print( myNumber, myString, tostring(myFunction) )

    -- OUTPUT:  1    1    function: 0x24a2e60

위 샘플 코드를 보세요.
결과 값을 보면 testFunc() 함수 안에서 선언한 n,s,f라는 로컬 변수에 다른 값을 대입시켰지만 이 함수 밖에서는 이 값이 바뀌지 않고 원래 값인 1,1이 출력 됩니다.



이 두 개의 차이를 잘 아셔야 실제 코딩에서 헛갈리지 않습니다. table만 direct reference를 합니다. 그러니까 Corona Display Objects 의 경우 테이블을 사용하니까 이것도 direct reference를 하겠죠? 고로 함수 안에서 로컬변수를 만들어서 Corona Display Objects를 바꾼 다면 함수 밖에서 최초에 선언했던 값도 바뀌겠죠?

Clearing the Reference

로컬 변수를 더 이상 사용하지 않을 때가 있을 겁니다. 또는 상위의 글로벌 값을 더 이상 사용하고 싶지 않을 때도 있구요. 이럴 경우 로컬 변수에 nil을 대입하면 됩니다.

    local myVar = myGlobal
    myVar = nil

이 경우 테이블의 경우는 어떻게 될 까요? 함수 안의 로컬 변수를 nil시키면 상위의 글로벌 테이블 변수의 값도 nil이 될까요?
정답은 그렇지 않다 입니다. 로컬을 nil시키면 이것은 로컬과 글로벌 변수와의 관계만 끊게 되기 때문에 상위의 글로벌 테이블 변수의 값까지 nil이 되지는 않습니다.

좀 헛갈리시나요?
이해가 되시면 잘 이해하세요. 프로그래밍할 때 아주 도움이 되실 겁니다.
잘 이해가 안 되신다면 일단 버릇을 들이세요. 나중에 이해할 때가 올겁니다.



오늘 까지는 프로그래밍 테크닉 중에서 퍼포먼스와 관련된 사항들을 알아 봤습니다.

다음 시간엔 외부 모듈과 패키지 사용법에 대해 알아 보겠습니다.
반응형

Corona SDK 프로그래밍 테크닉 1

2011. 11. 8. 20:54 | Posted by 솔웅


반응형

이번 시간하고 다음 시간엔 애플리케이션 퍼포먼스 및 메모리 관리에 대해 다룹니다.

아직까지 모바일 기계는 작기 때문에 CPU나 Memory 에 한계가 많습니다. 이로인한 속도 저하나 에러방지를 위해 신경써야할 퍼포먼스 및 메모리 관리에 대해 알아봅니다.


Performance and Optimization


앱 개발 할 때 항상 앱의 퍼포먼스에 대해 신경을 써야 합니다. 특히 아직까지 모바일은 메모리나 배터리 성능에 많은 한계가 있습니다. 

코로나에서는 garbage collection을 통해서 많은 부분을 자동으로 관리해 주고 있습니다.


코로나에서의 메모리 관리는 아래 다섯가지에 대해 고민 하면 됩니다.

1. Display objects

2. Global variables

3. Runtime Listeners

4. Timers

5. Transitions


메모리 낭비와 관련해서 체크할 방법이 있습니다.

아래 코드를 main.lua 파일 맨 아래에 넣으세요.

(main.lua말고 다른 파일에 넣어도 됩니다.)


local monitorMem = function()


    collectgarbage()

    print( "MemUsage: " .. collectgarbage("count") )


    local textMem = system.getInfo( "textureMemoryUsed" ) / 1000000

    print( "TexMem:   " .. textMem )

end


Runtime:addEventListener( "enterFrame", monitorMem )


MemUsage는 Lua 메모리를 나타냅니다. 그리고 TexMem은 그래픽 등이 사용하는 메모리를 나타냅니다. 여기서 중요한 것은 숫자가 얼마나 크냐가 아니고 앱이 진행 되면서 이 숫자가 어떻게 변하느냐를 보시는 겁니다.

스크린 1에서 2로 갔을 때 메모리 변화와 다시 1로 왔을 때의 메모리 변화를 보실 필요가 있습니다. 계속 늘어나기만 하면 어디에선가 메모리 누수가 있다는 얘기입니다.


Display Objects


디스플레이 오브젝트와 관련된 메모리 누수를 막는 방법은 객체를 정리할 때 항상 nil을 대입하는 겁니다.

display.remove( redBall )

redBall = nil



혹시 루핑을 돌면서 계속 객체를 새로 만들 경우 객체 remove를 하지 못하는 경우가 있는데요. 개발자는 항상 객체의 탄생과 소멸까지 책임 져야 합니다.


Global Variables


객체 생성할 때 local 을 붙이지 않으면 그것은 글로벌 변수입니다. 가능한 글로벌 변수보다 로컬 변수를 사용하는 것이 메모리 누수를 막는 방법입니다. 만약 사용하더라도 더이상 그 변수가 필요하지 않으면 반드시 nil 처리를 합니다. 그러면 루아의 garbage collector가 이것을 정리할 수 있습니다.


Runtime Listeners


display object를 remove할 때 이 객체에 붙어 있는 listener도 메모리에서 함께 해제 됩니다. Runtime에 리스너를 달게 되면 개발자가 직접 그 리스너를 remove할 때까지 메모리 해제 되지 않습니다. Runtime/enterFrame 리스너에서 일반적으로 일어나는 메모리 누수는 어느 한 screen에 Runtime 리스너가 달렸는데 그 스크린을 떠날때 이 리스너를 없애지 않는 경우 입니다. 이 경우 다음에 다시 이 스크린으로 돌아오게 되면 Runtime 리스너가 두개가 되기 때문입니다. 


Timers and Transitions


Timer와 Transition이 일반적으로 가장 crash를 많이 유발할 개연성이 있습니다. 예를 들어 time 하고 timer/transition start 사이에 end가 와 버리면 충돌 하게 됩니다. 또한 이것을 nil 처리 하지 않으며 이것은 메모리에 계속 남아 있으면서 좀 더 많은 메모리 누수를 유발합니다.


이것을 관리하는 효율적인 방법은 모든 timer와 transition들을 하나의 테이블(배열)로 관리하는 겁니다. 그러면 더이상 아무런 타이머와 트랜지션이 필요 하지 않을 때 한번에 nil처리 할 수 있습니다.


timerStash = {}

transitionStash = {}


function cancelAllTimers()

    local k, v


    for k,v in pairs(timerStash) do

        timer.cancel( v )

        v = nil; k = nil

    end


    timerStash = nil

    timerStash = {}

end


--


function cancelAllTransitions()

    local k, v


    for k,v in pairs(transitionStash) do

        transition.cancel( v )

        v = nil; k = nil

    end


    transitionStash = nil

    transitionStash = {}

end


아래는 timer와 transition 을 생성할 때의 예 입니다.

timerStash.newTimer = timer.performWithDelay( ...


transitionStash.newTransition = transition.to( myObject { ...


만약 cancel하지 말아야 될 타이머나 트랜지션은 이 테이블에 포함 시키지 않을 수 있습니다.


효과적으로 메모리 사용하기 


- 메모리 누수 방지하기 

- 가능한 리소스 파일 크기를 작게 하기

- 필요한 시점에 리소스 로드하기

- display object가 필요하지 않으면 display hierarchy 에서 remove 하기

나쁜 예)

-- rect is a global variable

rect = display.newRect(0,0,10,10)

rect:setFillColor(255,255,255)

 

local function removeOnTap( event )

   local t = event.target

   local parent = t.parent

 

   -- remove from display hierarchy

   -- but var "rect" still exists

   -- so memory is never freed

   parent:remove( t )

 

   return true

end

 

rect:addEventListener(   "tap", removeOnTap ) 


좋은 예)

-- rect is a local variable

local rect = display.newRect(0,0,10,10)

rect:setFillColor(255,255,255)

 

local function removeOnTap( event )

   local t = event.target

   local parent = t.parent

 

   -- remove from display hierarchy

   parent:remove( t )

 

   return true

end

 

rect:addEventListener(   "tap", removeOnTap ) 


위의 나쁜 예는 rect가 글로벌 변수로 선언이 돼 있기 때문에 parent:remove(t)를 해도 rect는 메모리에서 해제되지 않습니다. 좋은 예처럼 변수를 local로 처리하면 메모리가 깨끗하게 정리 됩니다.


Reducing Power Consumption (파워 소비 줄이기)

모바일 디바이스는 배터리 생명이 짧습니다. 개발자는 배터리 소비를 줄이기 위해 아래와 같은 사항들을 되도록 안 쓰도록 신경을 쓸 수 있습니다.

- Network traffic (Wi-Fi radios and baseband cell radios)

- GPS

- Accelerometers

- Disk accesses (reading/writing to files)


Network

위 요소들 중 네트워크 access가 가장 파워를 많이 사용합니다. 될 수 있는 대로 네트워크 트래픽을 줄여야 합니다.

아래 사항들을 참고 하세요.

- 필요할 때만 외부 네트워크 연결을 한다.

- 가능한 전달할 데이터의 사이즈를 최소화 한다.

- Transmit in bursts. More power is consumed the longer the radio is actively transmitting data. Therefore, transmit the data in bursts instead of spreading out the same data into smaller transmission packets over time.

- 위치 데이터는 GPS,cell, Wi-Fi 네트워크를 통해 얻어 집니다. 이 위치 데이터도 필요한 경우만 사용 합니다.



Graphics


Group objects



Turn off animations for non-visible objects

애니메이션이 non-visible이 될 경우 또는 그 객체가 스크린 밖에 위치할 때에는 가능한한 그 애니메이션을 멈춥니다.


Optimize image size

큰 이미지는 로드 할 때 더 많은 시간과 메모리를 소비합니다. 

이 큰 이미지가 더 이상 필요하지 않으면 parent group에서 이 객체를 remove합니다.

local image = display.newImage( "image.png" )

 

-- do stuff with image

 

image:getParent():remove( image )



Lua: Best Practice


컬 변수를 사용하라

글로벌 변수

for i = 1, 1000000 do 

   local x = math.sin(i) 

end  

컬 변수

local sin = math.sin 

for i = 1, 1000000 do 

   local x = sin(i) 

end 


특히 위와 같이 긴 프를 사용 할 경우 컬로 변수를 선하면 훨씬 가다. 위 드를 예로 들면 글로벌 변수 제는 컬 변수 다 30% 더 실행 시간이 느립다.


함수를 사용할 경우에 함수 밖에서 컬로 변수를 선언 하면 글로벌 변수도가 빠릅다.


글로벌

 function foo (x) 

   for i = 1, 1000000 do 

      x = x + math.sin(i) 

   end 

   return x 

end  


External local

local sin = math.sin 

function foo (x) 

   for i = 1, 1000000 do

      x = x + sin(i) 

   end 

   return x 

end 


이 경우도 글로벌 변수를 사용한 드가 30% 더 속도가 느립다.



x*0.5 x/2 다 빠릅다.

x*x x^2다 빠릅다.


배열에 객체 집어 넣기

t[#t+1] = itemtable.insert(t,item)다 빠릅다.


Constant Folding

i=111+111i=222 와 속도가 같습다. 하면 컴파일러는 그 값을 미리 계하기 때문입다.

1+2+x 는 (1+2) + x 로 주 되서 3+x와 같은 시간이 걸립다.

지만 x+1+2는  (x+1)+2로 주 되서 미리 계산하지 않아서 시간이 더 걸리게 됩다.


Cache properties in a local variable

어떤 값이 계속 사용된다면 Cashe에 올리는 것이 속도가 빠릅다.

Uncached

function foo (o)

   local n = 0

   for i = 1, 1000000 do

      -- lookup o.x each time 

      n = i + n * o.x

   end

   return n

end 


Cached

function foo (o)

   -- cache o.x before the loop

   local x = o.x

   local n = 0

   for i = 1, 1000000 do 

      n = i + n * x

   end 

   return n

end 



다음 시간에도 계속해서 여러 프로그래밍 테크닉에 대해서 알아 보겠습니다.

반응형

Corona SDK Native UI

2011. 11. 7. 23:45 | Posted by 솔웅


반응형

코로나 SDK의 native library는 다양한 native user interface를 제공합니다.

Activity Indicator

native.setActivityIndicator()

native.setActivityIndicator( true );
timer.performWithDelay( 10000,  function()
     native.setActivityIndicator( false )
end)
local bgImg = display.newImage( "background1.png" )

위 소스코드와 같이 true를 하면 아래 화면에서 보이는 것 처럼 디바이스 내의 Activity Indicator가 나옵니다. true인 동안에는 touch 같은 동작을 할 수 없게 됩니다. 이 소스코드는 10초동안 indicator가 true이고 그 이후는 평상시 처럼 동작하는 코드 입니다.



Alert
native.showAlert(title,message[,buttonLabels[,listener]])
popup alert 화면이 뜨고 거 화면에 버튼도 표시 됩니다. 애니메이션 같은 프로그램의 액티비티는 백그라운드에서 그대로 실행이 될 겁니다. 그러니까 게임 같은데서 replay를 위해 모두 멈춰야 되면 이 alert화면을 띄우기 전에 코딩으로 다 처리 해 줘야 되더라구요. 다만 touch 같은 유저와의 interactivity는 alert을 없애기 전 까지는 block 됩니다. button만 빼 놓으면 setActivityIndicator랑 조건이 비슷합니다.

title은 제목이고 message는 텍스트로 표시 될 내용입니다. 그 다음에 버튼을 표시하고 그 버튼을 누르면 실행할 리스너 함수를 넣을 수 있습니다.



아래 간단한 소스코드 보시겠습니다.

native.setActivityIndicator( true );
timer.performWithDelay( 3000,  function()
     native.setActivityIndicator( false )
end)
local bgImg = display.newImage( "background1.png" )

-- Handler that gets notified when the alert closes
local function onComplete( event )
        if "clicked" == event.action then
                local i = event.index
                if 1 == i then
                        -- Do nothing; dialog will simply dismiss
                elseif 2 == i then
                        -- Open URL if "Learn More" (the 2nd button) was clicked
                        system.openURL( "http://coronasdk.tistory.com" )
                end
        end
end
 
-- Show alert with five buttons
local alert = native.showAlert( "Corona", "Dream. Build. Ship.",
                                        { "OK", "Learn More" }, onComplete )

이 소스코드는 OK 와 Learn More 두개의 버튼이 뜨고 OK를 누르면 아무것도 안하고 Learn More를 누르면 위에 있는 웹 사이트로 가도록 한 코드 입니다.

이 showAlert에 넣을 수 있는 버튼의 갯수는 6개 까지 입니다. 이 버튼은 순서에 따라 event.index에 1~6번까지가 할당 됩니다.

event.action 에는 cancelled와 clicked 가 있습니다.

native.cancelAlert()
cancel버튼을 누르면 alert화면이 사라지지만 프로그래밍으로없애려면 이 구문을 씁니다. 예를 들어 alert화면이 뜨고 일정 시간 후에 자동으로 없어지게 만드는 기능 등에 사용 할 수 있겠죠?

-- Dismisses "alert" from previous code sample after 10 seconds
local function cancelMyAlert()
        native.cancelAlert( alert )
end
 
timer.performWithDelay( 10000, cancelMyAlert )


Fonts

native.newFont(name[,size])
원하는 폰트가 있으면 이 함수를 이용해서 폰트를 사용할 수 있습니다.

기본적으로는 아래 두 폰트를 사용할 수 있습니다.
native.systemFont , native.systemFontBold

native.getFontNames()를 통해서 사용 가능한 폰트들을 리턴 받을 수 있습니다.

Text Input

native.newTextField(left,top,width,height[,listener])
single-line textfield를 표시합니다.
앱 스토어에 올린 Spin the Bottle 1 개발 할 때 사용해 봤는데요. 이게 시뮬레이터에서는 지원이 안 됐습니다. 그래서 테스트 할 때마다 디바이스에 인스톨 하면서 테스트 해야 되서 불편하더라구요.
얼마전에 시뮬레이터에서도 지원이 된다고 해서 새 build 버전을 받았는데 아직 안정적이지 않아서 인스톨이 잘 안 되더라구요. 코로나 측에서 테스트 완료하고 곧 공개 할 것 같습니다.

TextField 의 property들은 아래와 같습니다.
object.align : left,center,right 가 있음
object.font : native.newFont()를 리턴합니다.
object.isSecure : 패스워드 같이 문자가 찍히지 않도록 합니다. 디폴트는 false로 문자가 찍히도록 돼 있습니다.
object.size : 텍스트의 크기
object.text : textfiend에 지정된 텍스트를 뿌려줍니다.

아래와 같은 메소드 들이 있습니다.
object:setTextColor(r,g,b[,a]) : 텍스트 칼라를 지정해 줍니다.



Listening for Keyboard Events
스마트폰에서 텍스트를 입력하려면 키보드가 나타납니다.
이 때 그 움직임을 catch 할 수 있는데요. 이것은 event.phase로 구분 합니다.
event.phase = "began" : 키보드가 나타났을 때
event.phase = "ended" : 텍스트 필드가 아니라 다른 필드를 누를 때 같이 사용자가 해당 텍스트 필드의 작업을 멈췄을 떄
event.phase = "submitted" : return 을 눌렀을 때

native.setKeyboardFocus(textField) : 키보드 포커스를 해당 텍스트 필드에 함. nil을 넣으면 포커스를 없애고 키보드를 사라지게합니다.


Supported Keyboard Types
input textfield에는 5가지 타입의 키보드가 지원 됩니다. 프로퍼티 이름은 "inputType"입니다.
numericField = native.newTextField( 50, 150, 220, 36, handlerFunction )
numericField.inputType = "number"

위 소스에서 number는 숫자만 입력할 수 있는 키보드가 나옵니다.
default는 일반적인 키보드 입니다.
phone 은 전화번호 입력을 위한 키보드 입니다.
url 은 웹 주소를 입력할 수 있는 키보드 입니다.
email 은 이메일 주소를 입력 할 수 있는 키보드 입니다.

Multiline Textfields
여러 줄을 입력할 수 있도록 하려면 텍스트 박스를 사용합니다.
native.newTextBox( left, top, width, height )
높이를 넘어가면 스크롤 바가 생깁니다.

프로퍼티들은 아래와 같습니다.
object.align : left,center,right 가 있습니다.
object.font : native.newFont()에 의해 리턴된 폰트 객체 입니다.
object.hasBackground 배경화면이 있으면 true이고 투명하면 false입니다.
object.size 텍스트 크기 입니다.
object.text 텍스트 박스 내의 문자 입니다.

메소드에는 칼라를 지정하는 메소드가 있습니다.
object:setTextColor(r,g,b[,a])


Web PopUps

이 웹 팝업을 사용하려면 아래와 같이 하면 됩니다.
native.showWebPopup( "http://coronasdk.tistory.com" )
특정 크기를 지정해 줄 수도 있습니다.
native.showWebPopup( 10, 10, 300, 300, "http://coronasdk.tistory.com" )

Web popup scaling
웹 팝업의 크기를 설정 하려면 아래와 같이 HTML 파일에 메타태그를 코딩해 넣으시면 됩니다.
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

웹 폰트 사이즈를 유지하려면 아래와 같이 CSS 코드를 추가합니다.
<style type="text/css">
html {
        -webkit-text-size-adjust: none;
}
</style>

Web Popup Options
웹 팝업 화면을 조정하려면 아래와 같은 6개의 파라미터로 조절 하실 수 있습니다.
native.showWebPopup( 10, 10, 300, 300, "http://coronasdk.tistory.com", {urlRequest=listener} )

옵션테이블의 아래 프로퍼티들을 사용하실 수 있습니다.

options.baseUrl : 베이스 url을 규정합니다.
options.hasBackground : 팝업에 백그라운드가 있는지 없는지에 대해 컨트롤 합니다.
options.urlRequest : 웹 페이지의 상대 경로를 사용할 수 있습니다. 예) interface/WebOverlay
<form action="corona:close">
        <input type="submit"/>
</form>
사용자가 웹 팝업의  Submit을 누르면 설정된 리스너 함수는 urlRequest 이벤트 객체를 보내집니다.

Removing the Web Popup
native.cancelWebPoppu()으로 팝업을 없앨 수 있습니다.

Handling Web Popup Events
옵션 테이블에 이벤트 핸들러를 urlRequest 프로퍼티에 제공하면 웹 팝업은 유저가 웹 페이지의 링크를 클릭할 때 이 이벤트를 핸들러에 전달됩니다. 아래와 같은 이벤트들이 전달 됩니다.
event.errorCode
event.errorMessage
event.name
event.url

이 이벤트 핸들러는 한번 클릭할 때마다 한번씩 실행됩니다.
function listener( event )
  --if no errors, then execute my code
  if event.errorMessage == nil then
          myOnClickHandler( event.url )
  end
  return true
end
 
local options = {
  baseUrl = system.ResourceDirectory,
  hasBackground = false,
  urlRequest = listener
}
 
native.showWebPopup( "test.html", options )

지난번 코로나에서 광고 다는 법 할 때 말한건데요.
코로나 SDK에서는 현재 공식적으로 inMobi 만 지원합니다.

그런데 이 웹 팝업을 이용해서 admob이나 iAd 같은 앱 광고도 넣을 수 있습니다.
공식적인 방법은 아니고 개발자들 끼리 방법을 개발해서 그 코드를 공유하고 있습니다.

인터넷을 찾아보시면 나올겁니다.
저도 이 방법을 배우게 되면 이곳에 글로 정리해 두겠습니다.

그럼...

반응형

SlideView 구현하기

2011. 11. 4. 22:36 | Posted by 솔웅


반응형
어떤 분이 질문을 하나 올려 주셨습니다.
비밀 댓글로 올려 주신걸로 봐서 구체적인 내용이 알려지길 원하시지는 않는 것 같네요.
그 분의 질문을 보면 SlideView 구현에 대해 알면 해결 될 수 있을 것 같습니다.
그래서 오늘은 SlideView에 대해서 알아 보도록 하겠습니다.


이 이미지는 Corona SDK를 깔면 기본으로 제공되는 샘플 코드 입니다.
사진을 좌우로 움직일수 있고 Terminal에 보면 현재 사진이 몇번 째 인지 그리고 dragDistance는 얼마인지 그리고 총 몇개의 이미지 중 몇번째인지 등의 정보가 나옵니다.

코로나 SDK에서 제공되는 샘플을 보면 원하는 기능을 생각보다 쉽게 구현하는 방법을 알 수 있습니다. 적극적으로 활용하기를 바랍니다.

일단 SlideView를 쉽게 구현하도록 코로나에서는 따로 클래스 파일을 제공합니다.

이 소스 코드도 열어서 분석 해 보시면 그렇게 어렵지는 않습니다.
그건 각자 해 보시고 오늘 글에서는 이 기능을 이용하는 방법을 살펴 보겠습니다.
일단 소스를 보겠습니다.

display.setStatusBar( display.HiddenStatusBar )

local slideView = require("slideView")
   
local myImages = {
    "myPhotos1.png",
    "myPhotos2.png",
    "myPhotos3.png",
    "myPhotos4.png"
}       

--slideView.new( myImages )
--slideView.new( myImages, "bg.png" )
slideView.new( myImages, nil, 40, 60 )

별거 없습니다. 이렇게 단 몇줄로 slideView 기능이 구현 됐습니다.
첫줄은 statusBar를 없애는 것이고
그 다음 줄이 slideView.lua를 이용하기 위해서 require 한 겁니다.
그리고 slideView에 넣을 이미지를 테이블(배열) 에 넣구요.
slideView.new()를 해 주시면 됩니다.
slideView.lua의 36번째 줄을 보시면
function new(imageSet,slideBackground,top,bottom) 으로 함수가 시작합니다.
전달하는 파라미터를 이미지세트와 백그라운드 이미지 그리고 top과 bottom값을 전달 할 수 있습니다.
아까 terminal에 뿌려줬던 텍스트들은 main.lua에 있지 않고 slideView.lua 파일 안에 있네요.
전체 소스 파일은 아래 파일을 다운 받으세요.


다음 예제를 소개해 드리겠습니다.


코로나 샘플 소스코드와 똑 같습니다. 다만 다른 점이 있다면 이미지세트를 불러오는게 아니라 다른 별도의 파일들을 불러오는 겁니다.
display.setStatusBar( display.HiddenStatusBar )

local slideView = require("slideView")
   
local mySlides = {
    "screen1",
    "screen2",
    "screen3",
}       

slideView.new( mySlides )

이것도 소스는 간단합니다. 단지 mySlides라는 테이블(배열)에 파일 이름이 들어가 있습니다.
대표로 screen1을 보시겠습니다.

module(..., package.seeall)

function new()
    local g = display.newGroup()
   
    local background = display.newRect(0,display.screenOriginY, display.contentWidth, display.contentHeight-display.screenOriginY)
    background:setFillColor(222, 222, 222)
    g:insert(background)
   
    local message = display.newText("Screen 1", 0, 0, native.systemFontBold, 16)
    message:setTextColor(0, 0, 0)
    message.x = display.contentWidth*0.5
    message.y = display.contentHeight*0.5
    g:insert(message)
   
    function g:cleanUp()
        g:removeSelf()
    end
   
    return g
end

첫번째는 다른 file(main.lua) 에서 require하려면 설정해 줘야 되는 모듈 부분입니다.
그리고 function new() 함수가 있습니다.
g라는 그룹이 그 다음줄에서 정위 되었구요. 배경 화면으로 사용될 사각형이 그려졌습니다. 이 사각형의 변수 이름은 background이고 color가 정해지고 그룹에 insert됐습니다.
그 다음에는 Screen이라는 텍스트를 message라는 변수에 담아서 display합니다.

이 샘플 예제는 아래 파일을 참조하세요.


Slide View 관련해서 알아 봤는데요.

혹시 코로나로 개발하시거나 공부하시면서 질문 사항 있으시면 주저마시고 댓글로 올려 주세요.

저도 찾아 보면서 공부가 많이 되네요.

혹시 질문 올리신 분께 충분히 답변이 됐는지 모르겠습니다.
더 질문이 있으시면 댓글 달아 주세요.

그럼....
반응형

Location and Maps

2011. 11. 4. 18:37 | Posted by 솔웅


반응형
Location and Maps

MapView는 구글 맵을 앱에서 사용할 수 있게 해 줍니다.
코로나에서의 MapView는 현재까지 iOS만 지원 됩니다. 안드로이드에서 안될 뿐만 아니라 코로나 시뮬레이터에서도 안 됩니다.
테스트 하려면 맥에 XCode 시뮬레이터 깔아 놓고 하던가 애플 디바이스를 구입하셔야 합니다.

Constructor
myMap =  native.newMapView(left,top,width,height)

특정 영역에 MapView를 표시하고 코로나 display object를 반환합니다. 이 object는 다른 display object처럼 움직이거나 회전할 수 있습니다.

Map attributes
myMap.mapType = "standard"
myMap.mapType = "satellite"
myMap.mapType = "hybrid"

mapType은 일반 타입의 지도, 위성에서 보는것 같은 타입의지도, hybrid지도를 선택할 수 있습니다.
안드로이드나 애플 앱을 이용해서 구글 맵 표시를 해 보셨다면 쉽게 이해 하실 겁니다.

myMap.isZoomEnabled = true
확대 축소를 가능하게 해 줍니다. 디폴트는 true입니다.

myMap.isScrollEnabled = true
스크롤을 가능하게 해 줍니다. 디폴트는 true 입니다.

myMap.isLocationUpdating = true
현재 위치를 표시할 수 있도록 합니다. 사용자가 이동하면 계속 업데이트 될 겁니다. 디폴트는 false입니다.

isVisible= myMap.isLocationVisible
표시되고 있는 지역 내에 현재 위치를 표시할 수 있는지 없는지를 리턴합니다.
이 값은 read only 입니다.


Map functions

latitude, longitude = myMap:getAddressLocation( "gough and post, sf" )
latitude, longitude = myMap:getAddressLocation( "120 university, palo alto, ca" )
latitude, longitude = myMap:getAddressLocation( "eiffel tower" )

주어진 스트링으로 검색해서 그 위도와 경도 값을 리턴합니다. 이것은 구글 맵 HTTP 메소드를 이용하게 됩니다. 지도에 마커를 표시할 수도 있고 해당 지점이 중앙으로 오도록 할 수도 있습니다.

myLocation = myMap:getUserLocation
사용자의 현재 위치를 반환합니다. 그 내부의 값들은 아래와 같습니다.

myLocation.longitude
myLocation.latitude
myLocation.altitude
myLocation.accuracy
myLocation.time
myLocation.speed
myLocation.direction
myLocation.isUpdating -- a Boolean that flags whether the location is currently updating

myMap:setRegion(latitude,longitude,latitudeSpan,longitudeSpan,isAnimated)

화면에 출력하는 지역을 새로운 지역으로 바꿉니다.

myMap:setCenter(latitude,longitude,isAnimated)

화면에 출력하는 지역을 해당 위도 경도를 중앙으로 하는 지역으로 바꿉니다.

myMap:addMarker(latitude,longitude,{title="Displayed Title", subtitle="subtitle text"})

지도위 특정 지점에 핀을 표시합니다. 그리고 그 핀을 터치하면 위 텍스트가 표시됩니다.

myMap:addMarker(latitude,longitude)
특정 지점에 핀을 표시합니다.

myMap:removeAllMarkers()
핀을 모두 제거합니다.

Address Lookup from Position (Reverse Geocoding)
위도와 경도는 대략적인 주소값으로 바꿀 수 있습니다. 이것을 하려면 구글의 reverse geocoding server에 해당 값을 주고 원하는 값을 받는 작업을 해야 합니다. 그러므로 이 결과 값은 구글이 가지고 있는 자료의 정확성에 따라서 오차가 날 수 있습니다.

이 기능을 사용하기 위해서 mapAddress 이벤트 리스너를 activate 시켜야 합니다. 이 리스너가 액티브 상태이면 nearestAddress() 함수로 근처의 주소 데이터를 가지고 올 수 있습니다.

local function mapAddressHandler( event )
    -- handle mapAddress event here
    print( "The specified location is in: " .. event.city .. ", " .. event.country )
end
 
myMap:nearestAddress( latitude, longitude )
 
Runtime:addEventListener( "mapAddress", mapAddressHandler )

이 이벤트 객체는 다음과 같은 attributes를 가진 핸들러 함수를 리턴합니다.
event.street -- the street name
event.streetDetail -- the street number (or other specifier for location on the street)
event.city -- the city or town
event.cityDetail -- additional city information, such as neighborhood
event.region -- the state, province, or similar region within the country
event.regionDetail -- the region below the state level (e.g., the county, in the U.S.)
event.postalCode -- the postal code
event.country -- the country name
event.countryCode -- the standard country abbreviation

만약에 에러가 있으면 event.isError 에 true값이 할당 됩니다.


위 지도 이미지들은 각각 mapType을 normal, satellite, hybrid로 한 것입니다.
소스를 볼까요?

display.setStatusBar( display.HiddenStatusBar )
_W = display.contentWidth;
_H = display.contentHeight;

-- Create a native MapView (requires XCode Simulator build or device build)
-- You can create multiple maps, if you like...
--
myMap = native.newMapView( 0, 0, _W, _H )
--myMap.mapType = "normal" -- other mapType options are "satellite" or "hybrid"
--myMap.mapType = "satellite"
myMap.mapType = "hybrid"

 
-- The MapView is just another Corona display object, and can be moved or rotated, etc.
myMap.x = display.contentWidth / 2
myMap.y = 120
 
-- Initialize map to a real location, since default location (0,0) is not very interesting
myMap:setCenter( 37.331692, -122.030456 )
 
local function callMap()
        -- Fetch the user's current location
        -- Note: in XCode Simulator, the current location defaults to Apple headquarters in Cupertino, CA
        local currentLocation = myMap:getUserLocation()
        local currentLatitude = currentLocation.latitude
        local currentLongitude = currentLocation.longitude
       
        -- Move map so that current location is at the center
        myMap:setCenter( currentLatitude, currentLongitude, true )
       
        -- Look up nearest address to this location (this is returned as a "mapAddress" event, handled above)
        myMap:nearestAddress( currentLatitude, currentLongitude )
end
 
-- A function to handle the "mapAddress" event (also known as "reverse geocoding")
--
local mapAddressHandler = function( event )
        local locationText =
                "Latitude: " .. currentLatitude ..
                ", Longitude: " .. currentLongitude ..
                ", Address: " .. event.streetDetail .. " " .. event.street ..
                ", " .. event.city ..
                ", " .. event.region ..
                ", " .. event.country ..
                ", " .. event.postalCode
               
        local alert = native.showAlert( "You Are Here", locationText, { "OK" } )
end
 
-- A listener for the address lookup result
-- (This could also be a table listener on the map itself, in case you have more than one simultaneous map.)
Runtime:addEventListener( "mapAddress", mapAddressHandler )
 
timer.performWithDelay( 1000, callMap )         -- get current location after 1 second

첫 세줄은 status바를 없애고 화면 너비와 높이를 구한 부분입니다.
첫번째로 myMap이라는 변수에 mapView를 대입합니다. native.newMapview를 이용하는데요 이때 x,y,너비,높이 를 지정해서 표시되는 지도영역의 크기를 설정할 수 있습니다.
이 영역은 코로나의 display object로서 그 위치와 크기를 재설정 할 수 있고 여러개를 만들수도 있습니다. 경우에 따라서는 움직이게 할 수도 있겠구요. 만약에 필요하다면 말이죠.

그 다음은 setCenter 로 위도와 경도를 맞춰 줍니다. 그러면 그 위도와 경도가 화면 중앙에 표시 될 겁니다.

그 다음 callMap() 함수에는 현재 유저가 있는 위치와 현재 위치의 위도 경도를 구해서 이것으로 setCenter를 다시 해 줍니다.

그리고 가장 가까운 곳의 주소지를 얻어 옵니다.

그 다음 mapddressHandler 함수에서는 위도, 경도, 거리, 도시, 지역, 국가, 우편번호 등의 정보를 표시할 수 있도록 해 줍니다.

마지막에는 이 두 함수를 불러올 리스너들이 있습니다.

코로나 SDK의 mapView도 아주 간편하게 사용할 수 있네요.

이 소스를 기본으로 이것 저것 많이 시도해 보시면 좋을 것 같네요.

맥이 있어야 되고  xCode가 세팅 돼 있어야 되든가 아이폰 같은 애플 디바이스가 있어야 되는 한계가 있지만요.

그럼...
반응형


반응형
Touch Events

사용자가 스크린을 터치 했을 때 hit 이벤트가 발생합니다. 그리고 이 이벤트는 우선 순위에 따라 스크린에 표시된 object들에 전달 됩니다. 우선순위에 있는 객체가 이 이벤트를 가로채서 사용했다면(handle) 그 이후의 객체들에게는 이 이벤트가 전달 되지 않습니다.
어떤 특정한 객체에 이벤트의 포커스를 맞추고 싶으면 display.getCurrentStage():setFocus(object)를 이용합니다. 지난 번 글에서 한번 설명한 적이 있습니다. 버튼 down시 이후에 일어나는 up은 이 버튼에만 적용되도록 하는 경우에 사용 됩니다.

touch(single touch)
event.name : touch
event.x : 터치된 곳의 x 좌표
event.y : 터치 된 곳의 y 좌표
event.xStart : touch의 began phase 일 때 x 좌표였던 곳
event.yStart : touch의 began phase 일 때 y 좌표였던 곳
event.phase
  : began : 손가락이 스크린에 닿는 순간
  : moved : 손가락이 스크린에 닿은 채로 움직이는 경우 (컴퓨터의 드래그 상태)
  : ended : 손가락이 스크린에서 떼어지는 순간
  : cancelled : system이 touch 이 tracking을 cancel한 시점

touch (multitouch)
여러 손가락이 스크린에 터치 됐을 경우 이 multitouch를 사용해야 합니다.
제가 만든 앱 중에 multi Player ping pong 이라는 앱에 이 기능을 적용했는데요.
1~4인용 게임이라서 여러명이 터치할 경우 이를 반영해야 했습니다.
코로나에서는 MultitouchFingers와 MultitouchButton (interface 폴더 아래) 라는 샘플코드를 제공 합니다.
-- 이 multitouch 와 ui.lua를 동시에 사용할 경우는 최신버전의 ui.lua를 받으셔야 합니다. 초창기 버전에서는 멀티터치 기능 지원에 제한이 있었나 봅니다.
이 코로나 멀티 터치는 NexusOne, HTC Incredible 같은 일부 안드로이드 폰에서 동작이 잘 안 될 수 있다고 합니다. 이건 그 디바이스에서 멀티터치 기능을 지원하지 않기 때문이라고 하는군요. 참고하세요.--
멀티터치는 위에 있는 모든 싱글터치에 있는 프로퍼티들을 다 가지고 있습니다.
그 외에 event.id와 event.time 프로퍼티가 추가로 더 있습니다.
멀티터치는 각 터치들의 구분을 event.id로 합니다. event.time은 터치 당시의 system.getTimer()입니다.

멀티터치 사용법
멀티터치를 사용하시려면 처음에 system.activate("multitouch") 를 해 주시면 됩니다. 이 선언을 하신 후 스크린의 두곳을 터치하면 코로나는 event.id로 이것을 따로 관리하게 됩니다.

싱글 터치에 있었던  Forcus는 stage:setFocus(object[,touchID]) 를 사용 합니다. 이 기능은 각 object에 대해 touchID별로 따로 포커스를 둡니다. 이 기능을 없애려면 stage:setFocus(object,nil)을 해 주시면 됩니다.

Custom Events
object:dispatchEvent(event)
코로나는 custom events를 지원한다고 합니다. 아래 소스를 보세요.
-- Create an object that listens to events
local image = display.newImage( "endinggreen.png" )
 
-- Setup listener
local myListener = function( event )
        print( "Event " .. event.name )
        print( "Target has width: " .. event.target.contentWidth )
end
 
image:addEventListener( "myEventType", myListener )
 
-- Sometime later, create an event and dispatch it
local event = { name="myEventType", target=image }
image:dispatchEvent( event )


보시면 myEventType 이라는 이벤트를 개발자가 직접 만들 수 있습니다.
이 소스는 image에 이벤트를 걸어서 이 이미지가 뜰 때 event.name (myEventType)과 이 이미지의 width가 나오도록 한 소스코드 입니다.

Timer
가끔 특정 함수를 일정한 시간 이후에 호출할 필요가 있습니다.
앱 개발을 하다 보면 일정한 속도로 이미지를 움직이던가 할 때 이 시간을 조절하면서 이용하는게 더 편할 때가 있습니다. 이럴때 timer.performWithDelay를 사용하면 편합니다.

timer.performWithDelay(delay,listener[,iterations])

delay는 밀리세컨드 milliseconds 이구요 listener는 동작될 함수를 넣어 주시면 됩니다. iterations는 반복 횟수로 0이면 앱이 실행되고 있는 한 무한대로 반복 됩니다.

 local function listener( event )
    print( "listener called" )
 end
 
 timer.performWithDelay(1000, listener )

local listener = {}
function listener:timer( event )
   print( "listener called" )
end
 
timer.performWithDelay(1000, listener )

위 두 소스코드는 똑같이 1초마다 listener함수를 불러옵니다. 위에것은 함수 리스너이고 아래것은 테이블 리스너 입니다. 이 Function Listener 와 Table Listener 의 차이점과 장단점은 지난 글에서 다뤘으니까 따로 설명은 하지 않겠습니다.

timer.cancel(timerId)

 local t = {}
 function t:timer( event )
    local count = event.count
    print( "Table listener called " .. count .. " time(s)" )
    if count >= 3 then
        timer.cancel( event.source ) -- after 3rd invocation, cancel timer
    end
 end

 -- Register to call t's timer method an infinite number of times
 timer.performWithDelay( 1000, t, 0 )

위 소스코드는 1초 간격으로 t 를 실행시키는 테이블 함수 입니다. 여기서 event.count가 3보다 크거나 같으면 이 timer를 cancel 하도록 만들었습니다.
timer를 cancel 하는 방법에 대한 예제 소스코드 입니다.

timer.pause(timerId) : 이 기능은 코로나 build version 2011.596 부터 가능합니다.
timer.resume(timerId) 기능도 2011.596 버전부터 사용이 가능합니다.

2 주전 쯤에 다운 받았을 때만 해도 안전한 버전이 591 이었습니다. 위 두 기능을 다운 받으려면 그 이후 버전을 받아야 겠네요.

참고로 안정성이 확인 되지 않은 시험판 버전은 유료 구매자에 한해서 받을 수 있을 겁니다.

지금까지 코로나 SDK 의 이벤트,리스너에 대해 알아 봤습니다.

다음 Codona SDK DOC 공부는 Location and Maps 입니다.

그럼 다음에 뵙겠습니다.
반응형


반응형
오늘은 우선 Function Listener와 Table Listener 에 대해서 알아보는 것으로 시작 하겠습니다.

local myListener = function( event )
        print( "Listener called with event of type " .. event.name )
end
Runtime:addEventListener( "touch", myListener )
Runtime:addEventListener( "enterFrame", myListener )

위 리스너는 function 리스너 입니다.
Runtime으로 시작했으니 Global 리스너네요. 하나는 touch에 걸고 다른 하나는 enterFrame에 리스너를 걸었습니다.
touch를 하면 "Listener called with event of type touch"가 나올것이고 가만히 있으면 touch대신 enterFrame이 계속 찍히게 될 겁니다.

두 이벤트 모두 myListener라는 함수를 호출하죠? 이건 함수 리스너입니다.
가끔 함수 리스너는 이 리스너가 발생할 때 특정 변수를 처리하는데 한계가 있습니다. 이럴 경우 object Listener (table Listener) 를 사용할 수 있습니다.

-- assume MyClass and MyClass:new() already exist
 
function MyClass:enterFrame( event )
        print( "enterFrame called at time: " .. event.time )
end
 
function MyClass:touch( event )
        print( "touch occurred at ("..event.x..","..event.y..")" )
end
 
local myObject = MyClass:new()
 
Runtime:addEventListener( "touch", myObject )
Runtime:addEventListener( "enterFrame", myObject )

object Listener 는 위와 같이 사용합니다.
(이 코드는 이미 MyClass가 생성 돼 있어야 실행 됩니다.)
처음 코드와 같이 Runtime으로 리스너를 달았지만 테이블 리스너를 사용해 MyClass:enterFrame, MyClass:touch 이렇게 특정 이벤트에 함수를 달기 때문에 enterFrame에만 있는 정보들 그리고 touch 에만 있는 정보들 등을 자유롭게 사용할 수 있습니다.

Runtime Events

Runtime Events에 대해 알아 보겠습니다.

enterFrame
이 enterFrame은 Runtime:addEventListener  API를 이용해서 작동시킬 수 있습니다. 각 frameTime마다 불려질 겁니다.

local myListener = function( event )
        print( "Listener called with event of type " .. event.name )
end
Runtime:addEventListener( "enterFrame", myListener )

아래와 같은 프로퍼티가 있습니다.
event.name : enterFrame 이라는 스트링이 반환 됩니다.
event.time : 앱 시작 부터 지금 까지의 시간이 밀리세컨드로 표시 됩니다.

System

앱 실행 중에 전화가 온다든가 하는 이유로 다른 일을 할 동안 앱이 계속 유지 되게 하는데 필요합니다.
아래와 같은 프로퍼티들이 있습니다.
event.name : system 스트링 반환
event.type - 아래와 같은 스트링이 반환됩니다.
 : applicationStart - 앱이 시작될 때 그리고 main.lua에ㅔ 있는 모든 코드가 실행 됐을 때 발생함
 : applicationExit - 유저가 앱을 끝낼때 실행 됨
 : applicationSuspend - 전화가 오거나 오랫동안 사용을 안 해서 화면이 까맣게 될 때 같이 앱이 계속 유지될 필요가 있을 때 발생합니다.
 : applicationResume - 앱이 다시 실행 될 때 발생합니다. 시뮬레이터에서는 시뮬레이터가 백그라운드에 있다가 다시 포그라운드로 올라 올 때 실행 됩니다.

Orientation

지난 시간에 예제를 통해서 봤는데요. 전화기의 방향이 바뀔 때 이벤트들이 발생합니다.
아래와 같은 프로퍼티들이 있습니다.
event.name : orientation
event.type : portrait, landscapeLeft, portraitUpsideDown, landscapeRight, faceUp, faceDown

accelerometer

이것은 전화기를 기울이는 대로 중력이 작용하도록 할 때 사용합니다.(제 경험상)
아래와 같은 프로퍼티들이 있습니다.
event.name : accelerometer
event.xGravity : x 축 의 중력 관련 가속도 acceleration
event.yGravity : y 축의 중력 관련
event.zGrabity : z 축의 중력 관련
event.xInstant : x 축의 순간 가속도 instantaneous
event.yInstant : y 축의 순간 가속도
event.zInstant : z 축의 순간 가속도
event.isShake : 전화기를 흔들어쓸 때

location (GPS)

GPS 하드웨어에 의해 발생되는 위치 이벤트 입니다.
event.name : location
event.latitude : 위도
event.longitude : 경도
event.altitude : 고도
event.accuracy : 정확도(몇 미터를 기준으로 파악할지 여부)
event.speed : 초당 미터 m/s 로 나타나는 순간 스피드
event.direction : 북쪽부터 시작하는 시계방향으로의 방향
event.time : location event의 UTC timestamp

에러가 났을 경우에는 아래 프로퍼티에 어떤 값이 할당 됩니다.
event.errorMessage : error description. 에러가 났을 때에만 나옵니다.
event.errorCode : 에러 메세지

heading (compass)

안드로이드에서는 event.magnetic 만 지원되고 event.geographic은 지원 되지 않습니다.
event.name : heading
event.geographic : geographic 북극을 기준으로 시계방향으로의 heading 방향
event.magnetic : magnetic 북극을 기준으로 시계방향으로의 heading 방향

memoryWarning

iOS에서만 지원되는 메모리 사용 관련 이벤트. 거의 5초 이내에 shut down 될 정도의 상황에서 발생.

local function handleLowMemory( event )
  print( "memory warning received!" )
end
 
Runtime:addEventListener( "memoryWarning", handleLowMemory )

Targeted Event

어떠한 단일 Target에 이벤트를 보냄

completion
오디오, 비디오 부분에서  예제로 다뤘었는데요. 오디오나 비디오가 완전히 끝났을 때 발생하는 이벤트 입니다.
event.name : completion

timer
event.name : timer
event.sorce : 타이머에 등록된 값
event.count : 타이머가 실행 된 횟수
event.time : 앱이 시작된 이후부터 지금까지의 시간

urlRequest

native.webPopup() 함수와 함께 등록되는 이벤트 입니다.
event.name : urlRequest
event.url : absolute URL
event.errorMessage : 에러 메세지 유저의 언어 세팅에 따라 표시 됨
event.errorCode : 에러 메세지 유저의 언어 세팅에 관계 없이 표시 됨

오늘은 빨리 작업할 일이 있어서 여기까지 밖에 정리하지 못하겠네요.
다음 시간에 Touch Events, Multi Touch Events 그리고 Timer에 대해 알아 보겠습니다.

감사합니다.

반응형


반응형
오늘 다룰 이슈는 코로나에서의 이벤트와 리스너 입니다.
이벤트, 리스너는 어떤 행위(이벤트) 가 일어났을 때 이를 감지(리스너) 하고 이에 대해 특정 행위를 하도록 하는 상호 작용 효과를 내는데 꼭 필요한 기능입니다.

글로벌 이벤트(Global Events)
어떤 이벤트 들은 광범위하게 적용 되는 겁니다. 예를 들어 enterFrame, system, orientatin등이 있습니다. 이미지,버튼,텍스트 같이 특정 객체(object)에 한정된 이벤트가 아니라 프로그램 전체적으로 영향이 있는 글로벌 이벤트 입니다.

local label = display.newText( "portrait", 0, 0, nil, 30 )
label:setTextColor( 255,255,255 )
label.x = display.stageWidth/2; label.y = display.stageHeight/2
 
local function onOrientationChange( event )
        label.text = event.type   -- change text to reflect current orientation
        -- rotate text so it remains upright
        local newAngle = label.rotation - event.delta
        transition.to( label, { time=150, rotation=newAngle } )
end
 
Runtime:addEventListener( "orientation", onOrientationChange )

위 소스 코드는 orientation 의 변화가 있으면 onOrientationChange 함수를 실행합니다.
핸드폰이 세워저 있으면 portrait 글자가 쓰여지고 옆으로 뉘어져 있으면 글자도 각도를 바꾸고 text도 바뀌는 함수 입니다.


orientationr과 관련된 cases는 상하좌우로 돌릴때랑 faceUp,faceDown 이렇게 6개가 있네요.


Local Events


Hit Events -  user가 스크린을 터치 하면 이 히트 이벤트가 생깁니다. 만약에 이 이벤트를 어떤 특정 객체(object)에 줬다면 이 hit 포인트의 좌표를 그 object가 가로 채서 사용하게 될 겁니다.


이벤트의 전달(전파)와 핸들링 (Propagation/Handling)

이 이벤트들은 특정한 순서에 따른 객체(objects)들을 통해 전파 됩니다. 디폴트로는 이벤트를 받기 위한 display hierarchy에 따른 첫번째 object가 그 이벤트를 갖게 될 겁니다. 쉽게말하면 일반적으로 가장 위에 display된 객체가 우선적으로 이벤트를 가로 채 가게 될 거라는 겁니다. 이 이벤트는 그 이벤트가 핸들(처리) 될 때까지 전파(전달) 될 겁니다. 그러니까 한 위치에 여러개의 객체(object)가 중복 돼 있고 그 위치를 hit 했다면 맨 위의 객체에게 전달 되고 그 객체가 핸들링을 하지 않으면 그 다음객체 또 핸들되지 않으면 그 다음 객체 ... 이런 순으로 이벤트가 각 객체들에 전달되고 맨 마지막에는 스크린 자체 객체(Runtime object)에 전달 될 겁니다.

만약에 겹쳐진 두개의 객체에서 핸들링 하도록 되 있다면 우선순위에 있는 객체에 이벤트가 전달되고 핸들링 되면 이 이벤트의 전달(전파)는 끝이 날 것이기 때문에 우선순위에 밀린 객체는 그 이벤트를 핸들링 할 수 없게 됩니다.


Overriding Propagation with Focus

Focus를 세팅함으로서 특정 오프젝트에 앞으로의 hit 이벤트를 redirect할 수 있습니다. 예를 들어 버튼을 터치 하면 다른 버튼 이미지로 바뀌도록 했을 경우를 상상해 보면, down 하면 이미지가 바뀌고 up 하면 원래 이미지로 돌아와야 되는데 user가 down한 후 up을 하지 않고 버튼 밖으로 나가서 up을 하게 되면 원래 이미지로 돌아오지를 못 합니다. 이 경우 앞으로 일어날 up이벤트를 이 버튼에 포커스를 맞추겠다는 의미로 이 setFocus 를 이용하면 어디에서  up을 하든지 이 버튼의 토글 기능은 제대로 작동 할 겁니다.

function button:touch( event )
        local phase = event.phase
        if "began" == phase then
                -- Subsequent touch events will target button even if they are
                -- outside the stageBounds of button
                display.getCurrentStage():setFocus( self )
        else
        ...
        end
        return true
end


Listener and Event Delivery


리스너는 함수이거나 테이블 객체 일 수 있습니다. 두 경우 모두 event 인수가 리스너에 전달 됩니다. 


함수 리스너(function Listener)

 local function listener( event )
   print("Call #"..event.count )
end
timer.performWithDelay(1000, listener, 5 )


테이블 리스너(Table Listener)

local listener = {}
function listener:timer( event )
   print("Call #"..event.count )
end
 
timer.performWithDelay(1000, listener, 5 )


위 소스코드는 timer 이벤트에서 listener라는 함수를 호출하고 있습니다.

위에것은 함수 리스너이고 아래것은 테이블 리스너 입니다.


Registering for Events


이벤트는 addEventListener라는 메소드를 통해서 등록합니다.  그리고 removeEventListener라는 메소드로 제거합니다.


    •    object:addEventListener( )
    •    object:removeEventListener( )


* Function Listener

local button =  display.newImage("button.png")
 
local function listener(event)
  print(event.name.."occurred")
  return true
end
 
button:addEventListener( "touch", listener )


* Table Listener

local button = display.newImage("button.png")
 
function button:touch(event)
  print(event.name.."occurred")
  return true
end
 
button:addEventListener( "touch", button )


위 두 소스 코드는 버튼 이미지에 이벤트리스너를 단 것입니다. 위에것은 함수 리스너이고 아래 것은 테이블 리스너 입니다.


객체가 아니라 시스템에 add하는 이벤트리스너는 아래와 같이 add합니다.


* Function Listener

local function listener(event)
  print(event.name.."occurred")
end
 
Runtime:addEventListener("enterFrame", listener )


* Table Listener

local listener = {}
 
function listener:enterFrame(event)
  print(event.name.."occurred")
end
 
Runtime:addEventListener("enterFrame", listener )


이제 이벤트 다는 법을 배웠습니다.

그런데 Function Listener와 Table Listener가 나오는데 두개의 차이점과 장단점이 무엇인지 궁금하지 않나요?


두 리스너의 차이점과 장단점에 대해서는 다음 글에서 다루겠습니다.

다음 글에서는 이 외에 이벤트의 종류와 timer에 대해서도 배워보겠습니다.



반응형

System과 OS Library

2011. 10. 31. 19:43 | Posted by 솔웅


반응형
오늘은 시스템과 operating system Library에 대해 알아 보겠습니다.


system.getInfo( param )
시스템 정보를 얻어오는 함수입니다.


시스템 함수를 사용해서 시스템 정보를 터미널에 뿌려주는 소스입니다.

아래 소스를 보면서 정리하겠습니다.

local sName = system.getInfo( "name" ) 
print("name = " .. sName);
디바이스의 이름을 출력합니다. iPhone에서는 iTunes에 나오는 이름이 출력됩니다.
local sModel = system.getInfo( "model" )
print("model = " .. sModel);
디바이스의 타입이 출력됩니다. (iPhone,iPad,iPhone Simulator,Droid,Galaxy Tab 등등)
local sDID = system.getInfo( "deviceID" )
print("deviceID = " .. sDID);
디바이스의 유니크한 아이디를 출력합니다.
local sEnv = system.getInfo( "environment" )
print("environment = " .. sEnv);
앱이 돌아가는 디바이스 환경을 출력합니다. 시뮬레이터인지 iOS인지 등등
local sPFN = system.getInfo( "platformName" )
print("platformName = " .. sPFN);
Mac OS X, Win, iPhone OS, Android 등 플랫폼(OS)의 이름을 출력합니다.
local sPFV = system.getInfo( "platformVersion" )
print("platformVersion = " .. sPFV);
플랫폼의 버전을 출력합니다.
local sVer = system.getInfo( "version" )
print("version = " .. sVer);
코로나 버전이 출력됩니다.
local sBul = system.getInfo( "build" )
print("build = " .. sBul);
local sTMU = system.getInfo( "textureMemoryUsed" )
print("textureMemoryUsed = " .. sTMU);
현재의 texture memory usage를 출력합니다.
local sMTS = system.getInfo( "maxTextureSize" )
print("maxTextureSize = " .. sMTS);
texture의 맥시멈 사이즈를 출력합니다.
local sArcInfo = system.getInfo( "architectureInfo" )
print("architectureInfo = " .. sArcInfo);
CPU architecture 정보를 출력합니다.
안드로이드는 주로 ARM, ARM Neon등이 출력되고 iOS는 iPhone1,1 iPhone1,2 등이 출력됩니다.

system.getPreference( category, name )

local sTime = system.getTimer()
print("system time = " .. sTime);
앱이 시작되고 난 다음의 시간이 출력됩니다.
local sURL = system.openURL( "http://coronasdk.tistory.com" )
if(sURL) then print("OK") else print("No") end
URL을 오픈합니다. 결과 값은 true,false가 출력됩니다.
local sPath = system.pathForFile( "main.lua" )
print("sPath = " .. sPath);
해당 파일이 있는 경로를 출력합니다.
-- Set the measurement interval to 50 Hz.
-- This makes the system take 50 measurements per second.
system.setAccelerometerInterval( 50 )
system.setIdleTimer( true )  -- enable (turn on) the idle timer
system.setLocationAccuracy( 10 )  -- set GPS accuracy to 10 meters
GPS정확도를 10미터로 합니다.
system.setLocationThreshold( 100 )  -- fire the location event every 100 meters
100미터마다 로케이션 이벤트를 줍니다.
system.vibrate()
진동을 줍니다.

System-defined directories

system.DocumentsDirectory -  persist하게 유지될 필요가 있는 파일에 사용됩니다.

system.TemporaryDirectory - 일시적으로 필요한 파일에 사용됩니다.

system.ResourceDirectory - 리소스가 있는 디렉토리 입니다. 다운 받거나 하게 되면 이곳에 파일이 저장 됩니다. 이곳에 있는 파일은 개발자 임의로 생성,제거,수정 하면 안됩니다. 앱이 실행 될 때 이곳의 정보를 읽기 때문에 이 정보가 맞지 않으면 앱이 실행되지 않을 수도 있습니다.

OS Library

다음은 OS 에 대한 정보 입니다.


아래 소스를 보면서 정리하겠습니다.
local clock = os.clock ()
print("clock = " .. clock);
CPU 타임 1초동안 프로그램이 사용한 대략적인 시간입니다.

local date = os.date( "*t" )    -- returns table of date & time values
print( date.year, date.month )  -- print year and month
print( date.hour, date.min )    -- print hour and minutes
print( os.date( "%c" ) )        -- print out time/date string: e.g., "Thu Oct 23 14:55:02 2010"
날짜를 포맷에 맞게 출력합니다.

local t1 = os.time()
 
-- Print the elasped time
local function dspTime()
        print( "Time elasped = " .. os.difftime( os.time(), t1) )
end
 
timer.performWithDelay( 2000, dspTime )  -- wait 2 second before calling

두 시간 동안의 차이를 출력합니다.

os.exit()   -- exit app
앱을 종료합니다.

local destDir = system.DocumentsDirectory  -- where the file is stored
local results, reason = os.remove( system.pathForFile( "apple.txt", destDir  ) )
 
if results then
   print( "file removed" )
else
   print( "file does not exist", reason )
end
--> file does not exist    apple.txt: No such file or directory
파일을 지웁니다.

local destDir = system.DocumentsDirectory  -- where the file is stored
local results, reason = os.rename( system.pathForFile( "orange.txt", destDir  ),
        system.pathForFile( "apple.txt", destDir  ) )
 
if results then
   print( "file renamed" )
else
   print( "file not renamed", reason )
end
--> file not renamed    orange.txt: No such file or directory

파일 이름을 새로 바꿉니다.

local t = os.date( '*t' )  -- get table of current date and time
print( os.time( t ) )      -- print date & time as number of seconds
--> 1287516614
t.min = t.min + 1         -- add one to the minute field
print( os.time( t ) )      -- print number of seconds (increases by 60 seconds)
-->  1287516674
현재의 시간을 출력합니다.

os.execute( "ls" )

해당 os 명령어를 실행 합니다.

오늘 사용했던 소스는 아래에 있습니다.

system과 OS에 관련한 함수들을 살펴 봤습니다.
잘 이용하면 앱 만드는데 꽤 유용하게 쓰일 수 있습니다.

궁금한 점은 댓글을 이용해 주세요.
그럼 다음에 뵙겠습니다.






반응형


반응형
지난번 Corona DOC 로 공부하면서 Sprite Sheets 는 직접 예제를 다루면서 한번 해 보기로 했죠?

오늘 직접 예제를 보면서 하겠습니다.


위 그림을 가지고 작업하겠습니다.
한개의 큰 이미지에서 부분만 잘라서 하나의 이미지처럼 사용하는 기법이 Sprite Sheets Animation 입니다.

이 애니메이션에서 가장 먼저 할 일은 sprite를 require하는 것이고 그 다음이 newSpriteSheet를 생성하는 겁니다.
이 newSpriteSheet를 하기 전에 개발자가 먼저 체크해 둬야 할게 있습니다.

sprite.newSpriteSheet( spriteSheetFile, [baseDir,]  frameWidth, frameHeight )
신택스는 위와 같은데요. spriteSheetFile은 이미지 이름이 들어가면 되구요. baseDir은 그냥 옵션 입니다. 그 다음이 sprite로 사용될 프레임의 너비와 높이를 넣어야 됩니다.
저 위 person.png 파일에서 보면 12개의 사람 이미지가 있는데 이 각 이미지의 너비와 높이를 말합니다.

아마 이걸 구할 수 있는 프로그램이 있을겁니다. 아니면 이걸 디자인한 디자이너에게 물어봐도 되구요. 그냥 포토샵 같은데서 값을 구해도 될 것 같은데...

저는 그냥 코로나에서 해 봤습니다.


보시면 x,y좌표가 각각 32.36이 나왔죠? 소스를 볼까요?

display.setStatusBar (display.HiddenStatusBar)
local _W,_H = display.contentWidth,display.contentHeight;

local bgImg = display.newImage ("background.png")
local person = display.newImage ("person.png")

local xLoc = display.newText("",_W/2, (_H/2) - 15, native.systemFontBold, 18);
local yLoc = display.newText("",_W/2, (_H/2) + 15, native.systemFontBold, 18);
xLoc:setTextColor(0,0,0)
yLoc:setTextColor(0,0,0)

    local function touchScreen(event)
        local x,y = event.x,event.y;
        local phase = event.phase;

        if phase == "began" then
            xLoc.text = "X= " .. x;
            yLoc.text = "Y= " .. y;
        elseif phase == "moved" then
            xLoc.text = "X= " .. x;
            yLoc.text = "Y= " .. y;
        elseif phase == "ended" then
            xLoc.text = "X= " .. x;
            yLoc.text = "Y= " .. y;
        end
    end

bgImg:addEventListener( "touch", touchScreen );

우선 작업하기 편하게 statusBar를 없애고 스크린 너비와 높이를 변수에 담습니다.
그리고 background.png와 person.png를 display합니다.
x,y좌표를 설정하지 않았으니까 디폴트로 0,0이 x,y좌표 일 겁니다.

그리고 가운데 좌표를 뿌려줄 텍스트를 빈칸으로 만들어 놓고 색을 검은색으로 설정했습니다.

맨 마지막 줄 보면 백그라운드 이미지에 리스너를 달았습니다.
그리고 touchScreen 함수를 보면요.
각 이벤트 마다(began,moved,ended) x,y좌표를 화면에 표시하도록 만들었습니다.

저는 마우스를 저 12개 사람 이미지 중 첫번째 뒷모습 이미지의 적당한 곳에 이동 시켰습니다.

그랬더니 x=32,y=36이 나왔네요. 전 이 값을 sprite의 너비와 높이로 사용 할 겁니다.

그럼 이제 본격적으로 sprite sheet animation을 만들어 볼까요?
들어가기에 앞서 4개의 이미지를 더 받아 보세요.

4개의 화살표 이미지 입니다. (이것도 사실 하나가지고 돌려가면서 쓸 수 있습니다. 메모리를 절약하시려면요.)

display.setStatusBar (display.HiddenStatusBar)
--> Hides the status bar

----------------------------------------------------------------------
--                                BASICS                                --
----------------------------------------------------------------------
require "sprite"
-- Very important!

local background = display.newImage ("background.png")
-- Sets the background

자 첫 부분은 편의상 statusBar를 없애는 코딩을 했습니다.
그리고 두번째로는 sprite sheets animation을 사용하기 위해서 sprite를 require 했습니다. 주석으로 아주 중요하다고 돼 있죠?
그 다음엔 백그라운드 이미지를 그렸습니다.

----------------------------------------------------------------------
--                                SPRITE                                --
----------------------------------------------------------------------
local herosheet = sprite.newSpriteSheet("person.png", 32, 36)
-- Our sprite sheet
-- 32 is the width of each "box", this is the image width divided by the number of images across
-- 36 is the height of each "box", this is the image height divided by the number of images down
   
    local heroset = sprite.newSpriteSet (herosheet, 1, 12)
    sprite.add (heroset, "heroleft", 10, 3, 300, 0)
    sprite.add (heroset, "heroright", 4, 3, 300, 0)
    sprite.add (heroset, "heroup", 1, 3, 300, 0)
    sprite.add (heroset, "herodown", 7, 3, 300, 0)
-- The sprite set uses images 1 to 12 (all of them)
-- "heroup" starts at image 1 and includes 3 frames. (In this case 1, 2, 3.)
-- The "300" indicates .3 seconds per frame, the "0" indicates it will repeat until we stop it.
   
    local hero = sprite.newSprite (heroset)   
    hero.x = 160
    hero.y = 200
-- We insert out hero sprite
   
    hero:prepare("herodown")
-- We prepare the sprite   

이제 sprite 이미지를 설정하겠습니다.
newSpriteSheet 신택스는 위에서 보셨죠?
person.png를 spriteSheet로 이용할 거고 각 프레임의 크기는 너비 32,높이 36을 할 겁니다.
그 다음 newSpriteSet을 합니다. 신택스는 아래와 같습니다.
sprite.newSpriteSet (spriteSheet, startFrame, frameCount)
위에 코드를 보면 스프라이트 세트로 herosheet을 쓸거고 프레임은 1번에서부터 12번까지 있다는 내용입니다.

sprite.add
sprite.add( spriteSet, sequenceName, startFrame, frameCount,time,[loopParam] )
파라미터를 보면 스프라이트 세트와 이름 그리고 시작 프레임과 프레임 숫자와 시간 그리고 루프 도는 횟수등이 들어갑니다.
위 코드를 보면
sprite.add (heroset, "heroleft", 10, 3, 300, 0)
heroset에 heroleft라는 이름으로 10프레임부터 3개 프레임을 0.3초 간격으로 표시를 하고 루프는 무한대라는 의미입니다.

sprite.newSprite
스프라이트의 새 인스턴스를 생성합니다. 한마디로 메모리 공간을 확보해 둔다는 의미겠죠. 스프라이트는 Corona DOC 강좌에서 살펴 봤듯이 DisplayObject 입니다.
신택스는 sprite.newSprite( spriteSet ) 입니다.

위 코드를 보면 heroset을 newSprite으로 정하고 x,y 위치를 지정했습니다.

prepare

스프라이트 인스턴스에서 실행되고 있는 애니메이션 시퀀스를 stop시킵니다. 그리고 이 시퀀스의 첫번째 프레임으로 갑니다. 루프 counter도 reset됩니다.
spriteInstance.play()가 사용되면 다시 플레이 됩니다.
신택스는 spriteInstance:prepare( [sequence] ) 입니다.

위의 코드에서는 hero 인스턴스를 herodown에서 stop된 상태로 준비 합니다.
person.png 이미지에서 보면 세번째 줄 첫번째 이미지가 나타나겠죠?

----------------------------------------------------------------------
--                                ARROWS                                --
----------------------------------------------------------------------   
up = display.newImage ("up.png")
up.x = 250
up.y = 380
---
down = display.newImage ("down.png")
down.x = 250
down.y = 440
---
left = display.newImage ("left.png")
left.x = 210
left.y = 410
---
right = display.newImage ("right.png")
right.x = 290
right.y = 410
-- The arrow images to move our sprite

그 다음은 화살표들을 display합니다.
아까 언급한 대로 한개의 이미지 가지고 rotate 시키면서 4개의 화살표를 만들 수 있습니다. 이건 여러분이 직접 해 보세요.
이 부분은 많이 다뤄본 부분이기 때문에 별다른 코멘트 없이그냥 넘어 갑니다.

----------------------------------------------------------------------
--                                MOVEMENT                            --
----------------------------------------------------------------------
local motionx = 0
local motiony = 0
local speed = 4
-- These are required below; change the speed if you wish to experiment but not motionx or motiony.

local function stop (event)
    if event.phase =="ended" then
        motionx = 0
        motiony = 0
        hero:pause()
    end
end
Runtime:addEventListener("touch", stop )
-- Here we state that we don't want the sprite animated or moving if we aren't pressing an arrow

local function movehero (event)
hero.x = hero.x + motionx
hero.y = hero.y + motiony
end
timer1 = timer.performWithDelay(1,movehero,0)
-- The function to move the hero; it's on a timer but you could also use a Runtime listener


function touchup (event)
motionx = 0
motiony = -speed
hero:prepare("heroup")
hero:play("heroup")
end
up:addEventListener("touch", touchup)
-- When the up arrow is touched, play hero up and move the hero upwards

function touchdown (event)
motionx = 0
motiony = speed
hero:prepare("herodown")
hero:play("herodown")
end
down:addEventListener("touch", touchdown)
-- When the down arrow is touched, play hero down and move the hero downwards

function touchleft (event)
motionx = -speed
motiony = 0
hero:prepare("heroleft")
hero:play("heroleft")
end
left:addEventListener("touch", touchleft)
-- When the left arrow is touched, play hero left and move the hero left

function touchright (event)
motionx = speed
motiony = 0
hero:prepare("heroright")
hero:play("heroright")
end
right:addEventListener("touch", touchright)
-- When the right arrow is touched, play hero right and move the hero right

이제 sprite도 모두 세팅 됐고 화살표도 세팅 됐으니 화살표를 누르면 animation이 일어나도록 할 차례입니다.

첫번째로 motionx,motiony,speed 변수를 생성합니다. 값은 0,0,4 로 설정해 둡니다.

Runtime:addEventListener("touch", stop )
그 다음 첫번째 이벤트 리스너로 Runtime 이벤트 리스너가 있습니다.
아무 화살표도 누르고 있지 않으면 애니메이션을 그 상태로 stop시키는 부분 입니다.
stop함수를 보면 motionx,motiony모두 0으로 세팅하고 hero 스프라이트는 pause()시킵니다.
마우스 up일 경우 이 함수가 실행 되게 됩니다.

timer1 = timer.performWithDelay(1,movehero,0)
그 다음은 timer 입니다. 위 코드는 0.001초마다 movehero를 실행한다는 의미 입니다.
맨 마지막 0은 루프로서 무한대를 의미합니다.
movehero함수를 보면 hero.x와 hero,y를 motionx와 motiony만큼씩 이동하도록 설정했습니다.
위 Runtime 리스너가 작동되면 motionx와 motiony 모두 0이니까 움직이질 않겠고 sprite도 pause돼 있으니까 정지 돼 있을 겁니다.

up:addEventListener("touch", touchup)
이제 위쪽 화살표에 리스너를 달았습니다.
그 내용을 보면 x좌표는 0이고 motiony를 -speed만큼씩 변화시킵니다.
speed는 4로 설정 돼 있고 Corona는 위로 올라 갈수록 y좌표가 줄어드니까 이렇게 되면 이미지는 위로 올라갈 겁니다.
그리고 play는 heroup을 설정했으니 이에 해당하는 3개의 프레임이 연달아 display될겁니다. 이 화살표를 누르고 있는 동안 timer가 계속 실행 될 겁니다.
(사실은 안 누르고 있을 때도 계속 실행됩니다.)
그럼 0.001초마다 motiony좌표를 4씩 마이너스 해 주고 timer에서 호출하는 movehero함수에서 hero 스프라이트 위치를 변경시켜 줍니다.
이럼으로서 스프라이트 이미지 3개가 번갈아 가면서 출력되고 그 위치도 4픽셀씩 바뀌니까 자연스러운 애니메이션 효과를 얻을 수가 있습니다.

나머지 버튼들도 마찬가지로 작동합니다.


이러면 화살표를 누르는 대로 이미지가 걸어가는 애니메이션 효과를 낼 수 있습니다.

아래 전체 소스코드와 이미지들이 있습니다.


오늘은 sprite sheets animation에 대해 자세히 알아 봤습니다
그럼 모두 즐거운 주말 되세요.

반응형