2014-01-16 26 views
0

我一直在努力幾個小時才能讓我的角色左右移動。遊戲的基本目標是讓角色跳起箱子。我有精靈的代碼,讓他走動所有的屏幕,但這樣他只移動在十在電暈/ Lua基本的側面運動

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) 
+0

請考慮在'updateGame'中更加一致地縮進代碼。 –

回答

0

您在x和y施加力,所以我的第一個猜測,我不能使它這個動作是沿着兩個軸發生的。

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

注意,你施加一個力的地方有差別,就像它在現實:如果你把一根棍子在它的中心,全粘不要在y方向加力移動,但如果你在一端(垂直於它)推動,它將旋轉,非常不同。

另請注意,您正在使用武力。力量改變當前議案。如果由於某種其他因素已經存在沿y的運動,則放置0力不會抵消y運動。如果你真的想約束y運動,可能有必要在每一幀(在update())中將速度設置爲0。

+0

知道這將是簡單的事情。非常感謝 – user3178851

+1

好,那麼請接受它,讓其他人知道它已被回答並解決了問題。 – Schollii