user1738357
user1738357

Reputation: 39

how to delay gotoscene

whenever the specific food hits the monkey, the game restarts but I want to delay it for few seconds and show some text before restarting but i cant seem to. It does not delay,

 local function monkeyCollision( self, event )
    if event.phase == "began" then
        if event.target.type == "monkey" and event.other.type == "food" then

            print( "chomp!" )
            event.other.alpha = 0
            event.other:removeSelf() 
            addToScore(5)
            -- get points!
        else
            print("ow!")
            monkey.alpha = 0
            monkey:removeSelf()
            displayScore = display.newText( "The total score is " .. score , 0, 0, "Helvetica", 30 )
             displayScore.x = screenLeft +150
            displayScore.y = screenRight-100
            displayre = display.newText( "  The game is going restart", 0, 0, "Helvetica", 25 )
    displayre.x = screenLeft +150
            displayre.y = screenRight-200
           storyboard.gotoScene("play", "fade", 1000) 
           end

Upvotes: 0

Views: 223

Answers (2)

joehinkle11
joehinkle11

Reputation: 512

Add a timer as Rob did like

timer.performWithDelay(5000, function() storyboard.gotoScene("play", "fade", 1000); end)

But you also have a problem now. What if you hit another food after you already hit one? This would make multiple timers go off and probably glitch because it will remove a monkey which was already removed...

local lostGame = false

local function monkeyCollision( self, event )
    if event.phase == "began" then
        if event.target.type == "monkey" and event.other.type == "food" then

            print( "chomp!" )
            event.other.alpha = 0
            event.other:removeSelf() 
            addToScore(5)
            -- get points!
        else

            if lostGame == false then
                print("ow!")
                monkey.alpha = 0
                monkey:removeSelf()
                displayScore = display.newText( "The total score is " .. score , 0, 0, "Helvetica", 30 )
                displayScore.x = screenLeft +150
                displayScore.y = screenRight-100
                displayre = display.newText( "  The game is going restart", 0, 0, "Helvetica", 25 )
                displayre.x = screenLeft +150
                displayre.y = screenRight-200
                timer.performWithDelay(5000, function() storyboard.gotoScene("play", "fade", 1000); end)

                lostGame = true
            end
        end
    end
end

By adding a variable to check if you have already lost, you can prevent it from running the code to leave while you are in the delay.

Upvotes: 2

Rob Miracle
Rob Miracle

Reputation: 3063

Why not put it in a timer:

timer.performWithDelay(5000, function() storyboard.gotoScene("play", "fade", 1000); end)

That will delay 5 seconds before calling storybaord.gotoScene()

Upvotes: 2

Related Questions