2013-04-22 61 views
0

我是Lua的新手,我試圖模擬角色移動。 我現在有角色左右移動。我希望角色一次移動16個像素。如果用戶沒有迅速觸摸手機,這可以正常工作。在這種情況下,角色會移動一個隨機數的像素。用Lua移動一個角色

我的問題是,我如何獲得觸摸事件,一次只註冊一次。

我的代碼:

-- move character 
function moveCharacter(event) 
    if event.phase == 'began' then 
     if event.x > character.x+8 then 
      transition.to(background, {time=800, x=background.x-16}) 
     end 

     if event.x < character.x-8 then 
      transition.to(background, {time=800, x=background.x+16}) 
     end 
    end 
end 

function touchScreen(event) 
    Runtime:removeEventListener('touch', moveCharacter) 

    if event.phase == 'began' then 
     Runtime:addEventListener('touch', moveCharacter) 
    end 

end 

Runtime:addEventListener('touch', touchScreen) 

回答

0

你可以試試這個:

function moveCharEF() 
    if event.x > character.x+8 then 
     background.x = background - 16 
    end  
    if event.x < character.x-8 then 
     background.x = background + 16 
    end 
end 

function moveCharacter(event) 
    if event.phase == 'began' then 
     display.getCurrentStage():setFocus(event.target) 
     event.target.isFocus = true 
     Runtime:addEventListener("enterFrame", moveCharEF) 
    elseif event.target.isFocus then 
     if event.phase == "ended" then 
      Runtime:removeEventListener("enterFrame", moveCharEF) 
      display.getCurrentStage():setFocus(nil) 
      event.target.isFocus = false 
     end 
    end 
end 

function touchScreen(event) 
    Runtime:removeEventListener('touch', moveCharacter) 

    if event.phase == 'began' then 
     Runtime:addEventListener('touch', moveCharacter) 
    end 

end 

Runtime:addEventListener('touch', touchScreen) 

順便說一句,我不知道您的應用程序。所以角色可能移動太快或太慢。只是改變moveCharEF()函數的相關行

0

是你在找什麼..?

local isTransitionInProgress = false 

local function resetFlag() 
    isTransitionInProgress = false 
end 

function moveCharacter(event) 
    if(event.x > character.x+8 and isTransitionInProgress==false) then 
    isTransitionInProgress = true 
    transition.to(background, {time=800, x=background.x-16,onComplete=resetFlag()}) 
    end 

    if(event.x < character.x-8 and isTransitionInProgress==false) then 
    isTransitionInProgress = true 
    transition.to(background, {time=800, x=background.x+16,onComplete=resetFlag()}) 
    end 
end 

background:addEventListener("tap", moveCharacter) 

保持編碼... :)

0

您可以嘗試使用,而不是 「觸摸」 的 「挖掘」 監聽器。它一次只記錄一次觸摸。

Runtime:addEventListener('tap', touchScreen)