Search code examples
androidmobileluacoronasdk

Corona SDK multitouch run and jump


I think this should be very easy to do, but I'm not able to find any solution. It's always just system.enable("multitouch") and then something with setFocus() method. I have a right button, that responds to touch event and makes player run right when held. Then I have a jump button, that responds to tap event, making player jump. Running works, jumping works, but when I run and try to jump nothing happens. Here is some code:

local speed = 3
local motionx = 0    
-- When right arrow is touched, move character right
    function right:touch()
        if string.find(player.sequence,"jump") then
            player:setSequence("jumpRight")
            motionx = speed;
        elseif string.find(player.sequence,"duck") then
            player:setSequence("duckRight")
        else
            player:setSequence("goingRight")
            motionx = speed;
        end
        player:play()
    end
    right:addEventListener("touch",right)

    -- When up arrow is tapped, jump character
    function jump:tap()
        if not isJumping then
            if string.find(player.sequence, "goingRight") then
                isJumping = true
                player:setSequence("jumpRight")
                player:setLinearVelocity(0,-120)
            end
            if string.find(player.sequence, "goingLeft") then
                isJumping = true
                player:setSequence("jumpLeft")
                player:setLinearVelocity(0,-120)
            end
            if string.find(player.sequence, "duckLeft") then
                player:setSequence("goingLeft")
            end
            if string.find(player.sequence, "duckRight") then
                player:setSequence("goingRight")
            end
            player:play()
        end
    end
    jump:addEventListener("tap",jump)

    -- Move character
    local function movePlayer (event)
        player.x = player.x + motionx;
    end
    Runtime:addEventListener("enterFrame", movePlayer)

I don't knowh where, how or why should I use the setFocus() method. But so far when running, I cannot jump until I release the right button.


Solution

  • It was my mistake, that I wanted to use TAP event for jump. I guess since it is called multiTOUCH it only works with multiple TOUCH events :) I changed TAP events to TOUCH events and added:

    if event.phase == "began" then
            display.getCurrentStage():setFocus( event.target, event.id )
            --other code
    end
    if event.phase == "ended" or event.phase == "cancelled" then
            display.getCurrentStage():setFocus( event.target, nil )
    end
    

    Now it works nicely.