2013-04-22 68 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)