在Corona/Lua中进行基本的左右移动。

我已经尝试了几个小时来让我的角色左右移动。这个游戏的基本目的是让角色跳到箱子上。我有使它在整个屏幕上移动的精灵代码,但我不能让它只在X轴上移动。

local touchX, touchY

local touchScreen = function(e)
    --print(e.phase, e.x, e.y)
    if e.phase == "began" then
        touchX = e.x
        touchY = e.y
    elseif e.phase == "moved" then
        --spriteAsh.x = spriteAsh.x + (e.x - touchX)
        --spriteAsh.y = spriteAsh.y + (e.y - touchY)
        local difX = e.x - touchX
        local difY = e.y - touchY

        spriteAsh:applyForce(difX *50, difY * 50, spriteAsh.x, spriteAsh.y)

        touchX = e.x
        touchY = e.y
    elseif e.phase == "ended" then

    end

end
Runtime:addEventListener("touch", touchScreen)

local updateGame = function(e)

    local seq
    local velX, velY = spriteAsh:getLinearVelocity()
    print (velX, velY)

    if math.abs (velX) >= math.abs (velY) then
            --horizonal
        if velX > 0 then
        seq  ="right_run"
                    else
            seq = "left_run"
                end

        else
        if velY > 0 then
        seq = "down_run"
        else
         seq = "up_run"

        end

    end

    if spriteAsh.sequence ~= seq then
    spriteAsh:setSequence(seq)
    spriteAsh:play()
    end

end
Runtime:addEventListener("enterFrame", updateGame)
点赞
用户869951
用户869951

你正在同时施加x和y方向的力,所以我的第一猜测是这将沿着两个轴发生运动。不要在y方向施加力:

spriteAsh:applyForce(difX *50, 0, spriteAsh.x, spriteAsh.y)

请注意,施加力的位置很重要,就像在现实中一样:如果你在一根木棍的中心推它,整根木棍会运动,但如果你在一个端点上推(垂直于它),它会旋转,完全不同。

还要注意,你正在施加力。力会改变当前运动状态。如果已经有y方向上的运动,因为其他因素,那么放置0力将不能取消y方向上的运动。如果你真的想限制y方向上的运动,每帧将速度设置为0可能值得在update()中执行。

2014-01-16 20:21:27