使用Lua移动角色

我对Lua不熟悉,正在尝试模拟角色移动。

我目前正在使角色左右移动。我希望角色每次移动16像素。如果用户不快速触碰手机,这很好。在这种情况下,角色将移动随机像素。

我的问题是,如何使触摸事件一次只注册一次。

我的代码:

-- 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)
点赞
用户2186639
用户2186639

你可以试试这个:

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()函数的相关行即可。

2013-04-23 00:46:22
用户1979583
用户1979583
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)

这是一个控制角色移动的函数,当屏幕被点击时会触发 moveCharacter 函数。如果点击的位置在角色右侧且没有其他转换正在进行,就会触发向左的转换;如果点击的位置在角色左侧且没有其他转换正在进行,就触发向右的转换。每次转换完成后都会通过 resetFlag 函数重置标志位 isTransitionInProgress

2013-04-23 09:05:44
用户2130287
用户2130287

你可以尝试使用“tap”侦听器来代替“touch”,它每次只能注册一个触摸。

Runtime:addEventListener('tap', touchScreen)
2013-04-29 02:52:03