在 Corona SDK 中,如何让一个对象在触摸背景屏幕时保持移动?

这是情况。我希望一个正方形物体在我触摸屏幕的同时,沿着 y 方向连续移动。基于代码,我应该得到一个连续移动的正方形物体,但是只有当我在触摸屏幕上滑动手指时,对象才会移动。我希望当我在屏幕上触摸同一位置时,正方形物体能够持续移动。

我尝试使用定时器和运行时事件监听器,但都没有成功。有什么解决方法?

_W = display.contentWidth
_H = display.contentHeight

local background = display.newRect(0,0,_W,_H)
background.anchorX = 0
background.anchorY = 0

local squareTimer

local function squareMoveUp()
     square.y = square.y - 5
end

local holding = 'false'
local function startMove(event)

     if event.phase == 'began' then
        --Runtime:addEventListener('enterFrame',squareMoveUp)
        squareTimer = timer.performWithDelay(200,squareMoveUp,0)

     elseif event.phase == 'ended' then
        --Runtime:removeEventListener('enterFrame',squareMoveUp)

     end
     return true
end

background:addEventListener('touch',squareMoveUp)
点赞
用户3041972
用户3041972

这个代码能够用你自己的对象替换方块:

_W = display.contentWidth
_H = display.contentHeight

local background = display.newRect(0,0,_W,_H)
background.anchorX = 0
background.anchorY = 0

local square = display.newRect(200,200,_W/3,_H/3)
square:setFillColor( 1,1,0 )

local squareTimer
local touchStarted = false

local holding = 'false'
local function startMove(event)

     if event.phase == 'began' then
        --Runtime:addEventListener('enterFrame',squareMoveUp)
        squareTimer = timer.performWithDelay(200,squareMoveUp,0)
        touchStarted = true
            local function squareMoveUp( )
                square.y = square.y - 0.02
            end

        for i = 1,1000 do
          if touchStarted then
                    squareTimer = timer.performWithDelay(200,squareMoveUp,1)
        end
    end

    elseif ( event.phase == "ended" ) then
            touchStarted = false
     end
     return true
end

background:addEventListener('touch',startMove)
2016-04-20 04:33:22
用户4327598
用户4327598

你需要将你的代码修改成以下的样子:

_W = display.contentWidth
_H = display.contentHeight

local background = display.newRect(0,0,_W,_H)
background.anchorX = 0
background.anchorY = 0

local square = display.newRect(200,200,_W/3,_H/3)
square:setFillColor( 1,1,0 )

local touchStarted = false

local function startMove(event)

    local function squareMoveUp( )
        if touchStarted then
            transition.moveTo( square, { y=square.y-10, time=1 } )
        end
    end

    if event.phase == 'began' then
        touchStarted = true
    elseif ( event.phase == "ended" ) then
        touchStarted = false
    end

    timer.performWithDelay(200,squareMoveUp,0)
end

background:addEventListener('touch',startMove)

或者你也可以在squareMoveUp函数中修改代码为:transition.moveTo( square, { y=square.y-10, time=1 } ) 而不是 square.y = square.y - 10。这样更加平滑。

2016-04-24 10:50:46