如何阻止物体移动经过一个点

时间:2016-05-09 09:48:58

标签: lua corona

我想知道是否有办法阻止物体离开屏幕。在我的代码中,我有一个可控制的字符(播放器),我想阻止它在x坐标为<时向左移动。 1

我尝试在下面的代码中执行此操作,但是,如果按住左箭头键,播放器将不会停止。

有没有办法解决这个问题?如果我有猜测,我会以某种方式需要我的程序不断检查player.x< 1

motionx = 0; -- Variable used to move character along x axis
speed = 10; -- Set Walking Speed


local function moveplayer (event)
    player.x = player.x + motionx;
end

Runtime:addEventListener("enterFrame", moveplayer)

local function onKeyEvent( event )
    if ( event.phase == "down" ) then
        if ( event.keyName == "left" ) and player.x > 1 then
            motionx = -speed
            return true
        elseif ( event.keyName == "right" ) then
            motionx = speed
            return true
        end
    end
end

Runtime:addEventListener( "key", onKeyEvent )

3 个答案:

答案 0 :(得分:0)

只需实现一个检查对象位置与屏幕边界的功能。只要它到达屏幕的边界,就会停止它。

要检查每个帧的对象位置,请将您的函数添加为事件“enterFrame”的事件侦听器。

阅读本文了解详情: https://docs.coronalabs.com/guide/events/detectEvents/index.html

当然,您也可以通过在屏幕周围放置隐形墙来使用碰撞引擎,这样只要碰到边框,物体就会反弹回来。

答案 1 :(得分:0)

你相当接近,但可能需要你的整个代码来测试它。我只改变了这个player.x< 1并移动)

motionx = 0; -- Variable used to move character along x axis
speed = 10; -- Set Walking Speed


local function moveplayer (event)
    player.x = player.x + motionx;
end

Runtime:addEventListener("enterFrame", moveplayer)

local function onKeyEvent( event )
    if ( event.phase == "down" ) then
        if ( event.keyName == "left"  and player.x < 1) then
            motionx = -speed
            return true
        elseif ( event.keyName == "right" ) then
            motionx = speed
            return true
        end
    end
end

运行时:addEventListener(“key”,onKeyEvent)

答案 2 :(得分:0)

您需要检查边界并将motionx设置为零:

local player = display.newCircle(display.contentCenterX, display.contentCenterY, 10)

local motionx = 0; -- Variable used to move character along x axis
local speed = 10; -- Set Walking Speed

local function moveplayer( event )
    player.x = player.x + motionx;
    if player.x < 0 then
        player.x = 0
        motionx = 0
    elseif player.x > display.contentWidth then
        player.x = display.contentWidth
        motionx = 0
    end
end

Runtime:addEventListener( "enterFrame", moveplayer )

local function onKeyEvent( event )
    if event.phase == "down" then
        if event.keyName == "left" then
            motionx = -speed
            return true
        elseif event.keyName == "right" then
            motionx = speed
            return true
        end
    end
end

Runtime:addEventListener( "key", onKeyEvent )