티스토리 뷰

AnscaMobile 홈페이지에 검색하면 나오는 인기있는 글에도 이미지를 드래그하는 것에 대해서 다루고 있습니다.
하지만 제가 그 소스로 만들었을 때 발견한 문제점이 있는데, 바로 드래그를 너무 빨리 해서 드래그를 하다가 터치 이벤트의 위치가 이미지 위가 아닐 경우에는 포커스를 놓치는 문제점이 발생됩니다.

그래서 어떻게 해야할지 방법을 찾다가 샘플 소스에서 그 답을 찾았습니다.
소스 상태가 상당히 쾌적해서 그대로 복사 붙여넣기 해도 됩니다.
저 같은 경우에는 양 그림(Image/Object/sheep.png)을 이용하였습니다.
저작권 문제가 될까봐 소스를 그대로 올릴테니 영어로 된 주석을 잘 보시면 될 것 같습니다.
소스가 같이 있으니 영어 주석을 읽는데 어려움은 별로 없을겁니다.


module( ..., package.seeall )


local function onTouch( event )

local t = event.target


-- Print info about the event. For actual production code, you should

-- not call this function because it wastes CPU resources.


local phase = event.phase

if "began" == phase then

-- Make target the top-most object

local parent = t.parent

parent:insert( t )

display.getCurrentStage():setFocus( t )


-- Spurious events can be sent to the target, e.g. the user presses 

-- elsewhere on the screen and then moves the finger over the target.

-- To prevent this, we add this flag. Only when it's true will "move"

-- events be sent to the target.

t.isFocus = true


-- Store initial position

t.x0 = event.x - t.x

t.y0 = event.y - t.y

elseif t.isFocus then

if "moved" == phase then

-- Make object move (we subtract t.x0,t.y0 so that moves are

-- relative to initial grab point, rather than object "snapping").

t.x = event.x - t.x0

t.y = event.y - t.y0

elseif "ended" == phase or "cancelled" == phase then

display.getCurrentStage():setFocus( nil )

t.isFocus = false

end

end


-- Important to return true. This tells the system that the event

-- should not be propagated to listeners of any objects underneath.

return true

end


function newSheep( params )


local sheep = display.newImage( "Image/Object/sheep.png" )

sheep.x = params.x

sheep.y = params.y

sheep:addEventListener( "touch", onTouch )

return sheep


end


newSheep으로 양을 생성합니다.
게임씬에서 newSheep에 테이블로 파라미터를 넘겨줍니다.
인자를 저렇게 파라미터 테이블로 한 이유는, 지금은 저렇게 인자를 간단히 쓰고 있지만 혹시 나중에 더 추가될 인자가 있는 것을 대비해 저렇게 코드를 구성하였습니다.
위의 onTouch( event ) 부분이 샘플 코드에 있던 내용인데요. 이벤트를 터미널에 출력하는 부분을 제가 임의로 삭제하였습니다. 제게 필요 없는 부분이었기 때문이죠. 그 onTouch( event ) 리스너를 newSheep에서 만든 객체에 추가해주면 끝입니다.

 
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday