How to switch scene

Hey guys!

I tried a lot to switch scene to my menu, but i had a lot of bugs and my game scene didn’t disappear , so idk what to do… Can u help me to switch scene?

local widget = require “widget”

local composer = require( “composer” )

local scene = composer.newScene()

function scene:create( event )


local sceneGroup = self.view

local appodeal = require( “plugin.appodeal” )

local composer = require “composer”

local gameStatus = 0

local yLand = display.actualContentHeight - display.actualContentHeight*0.2

local hLand = display.actualContentHeight * 0.1

local xLand = display.contentCenterX

local yBird = display.contentCenterY-50

local xBird = display.contentCenterX-50

local wPipe = display.contentCenterX+10

local yReady = display.contentCenterY-140

local uBird = -200

local vBird = 0

local wBird = -320

local g = 800

local dt = 0.025

local score = 0

local bestScore = 0

local scoreStep = 5

local bird

local land

local title

local getReady

local gameOver

local emitter

local board

local scoreTitle

local bestTitle

local silver

local gold

local pipes = {}

local function loadSounds()

  dieSound = audio.loadSound( “Sounds/sfx_die.wav” )

  hitSound = audio.loadSound( “Sounds/sfx_hit.wav” )

  pointSound = audio.loadSound( “Sounds/sfx_point.wav” )

  swooshingSound = audio.loadSound( “Sounds/sfx_swooshing.wav” )

  wingSound = audio.loadSound( “Sounds/sfx_wing.wav” )

  boomSound = audio.loadSound( “Sounds/sfx_boom.wav” )

end

local function calcRandomHole()

   return 100 + 20*math.random(10)

end

local function loadBestScore()

  local path = system.pathForFile( “bestscore.txt”, system.DocumentsDirectory )

– Open the file handle

  local file, errorString = io.open( path, “r” )

  if not file then

    – Error occurred; output the cause

    print( "File error: " … errorString )

  else

    – Read data from file

    local contents = file:read( “*a” )

    – Output the file contents

    bestScore = tonumber( contents )

    – Close the file handle

    io.close( file )

end

file = nil

end

local function saveBestScore()

– Path for the file to write

  local path = system.pathForFile( “bestscore.txt”, system.DocumentsDirectory )

  local file, errorString = io.open( path, “w” )

  if not file then

    – Error occurred; output the cause

    print( "File error: " … errorString )

  else

      file:write( bestScore )

      io.close( file )

  end

  file = nil

– show appodeal ad

  appodeal.show()

end

local function pause()

composer.removeScene(‘scenes.game’)

composer.gotoScene( “scenes.menu”, “fade”, 500 )

return true

end

local function status()

gameStatus=4

end

local function setupBird()

  local options =

  {

      width = 70,

      height = 50,

      numFrames = 4,

      sheetContentWidth = 280,  – width of original 1x size of entire sheet

      sheetContentHeight = 50  – height of original 1x size of entire sheet

  }

  local imageSheet = graphics.newImageSheet( “Assets/bird.png”, options )

  local sequenceData =

  {

      name=“walking”,

      start=1,

      count=3,

      time=300,

      loopCount = 2,   – Optional ; default is 0 (loop indefinitely)

      loopDirection = “forward”    – Optional ; values include “forward” or “bounce”

  }

  bird = display.newSprite( imageSheet, sequenceData )

  bird.x = xBird

  bird.y = yBird

end

local function prompt(tempo)

  bird:play()

end

local function initGame()

  score = 0

  scoreStep = 10

  title.text = score

–  title.text = hLand

  for i=1,3 do

    pipes[i].x = 400 + display.contentCenterX * (i-1)

    pipes[i].y =  calcRandomHole()

  end

  yBird = display.contentCenterY-50

  xBird = display.contentCenterX-50 

  getReady.y = 0

  getReady.alpha = 1

  gameOver.y = 0

  gameOver.alpha = 0

  board.y = 0

  board.alpha = 0

  audio.play( swooshingSound )

  transition.to( bird, { time=300, x=xBird, y=yBird, rotation = 0 } )

  transition.to( getReady, { time=600, y=yReady, transition=easing.outBounce, onComplete=prompt   } )

  

end

local function wing()

  if gameStatus==0 then

    gameStatus=1

    getReady.alpha = 0

  end

  if gameStatus==1 then

    vBird = wBird

    bird:play()

    audio.play( wingSound )

  end

  if gameStatus==3 then

    gameStatus=0

    initGame()

  end

end

local function  setupExplosion()

  local dx = 31

  local p = “Assets/habra.png”

  local emitterParams = {

          startParticleSizeVariance = dx/2,

          startColorAlpha = 0.61,

          startColorGreen = 0.3031555,

          startColorRed = 0.08373094,

          yCoordFlipped = 0,

          blendFuncSource = 770,

          blendFuncDestination = 1,

          rotatePerSecondVariance = 153.95,

          particleLifespan = 0.7237,

          tangentialAcceleration = -144.74,

          startParticleSize = dx,

          textureFileName = p,

          startColorVarianceAlpha = 1,

          maxParticles = 128,

          finishParticleSize = dx/3,

          duration = 0.75,

          finishColorRed = 0.078,

          finishColorAlpha = 0.75,

          finishColorBlue = 0.3699196,

          finishColorGreen = 0.5443883,

          maxRadiusVariance = 172.63,

          finishParticleSizeVariance = dx/2,

          gravityy = 220.0,

          speedVariance = 258.79,

          tangentialAccelVariance = -92.11,

          angleVariance = -300.0,

          angle = -900.11

      }

      emitter = display.newEmitter(emitterParams )

      emitter:stop()

    end

local function explosion()

  emitter.x = bird.x

  emitter.y = bird.y

  emitter:start()

end

local function crash()

  gameStatus = 3

  audio.play( hitSound )

  gameOver.y = 0

  gameOver.alpha = 1

  transition.to( gameOver, { time=600, y=yReady, transition=easing.outBounce } )

  board.y = 0

  board.alpha = 1

  

  if score>bestScore then

    bestScore = score

    saveBestScore()

  end

  bestTitle.text = bestScore

  scoreTitle.text = score

  if score<10 then

    silver.alpha = 0

    gold.alpha = 0

  elseif score<50 then

    silver.alpha = 1

    gold.alpha = 0

  else

    silver.alpha = 0

    gold.alpha = 1

  end

  transition.to( board, { time=600, y=yReady+100, transition=easing.outBounce } )

  

end

local function collision(i)

  local dx = 40 – horizontal space of hole

  local dy = 50 – vertical space of hole

  local boom = 0

  local x = pipes[i].x

  local y = pipes[i].y

  if xBird > (x-dx) and xBird < (x+dx) then

    if yBird > (y+dy) or yBird < (y-dy) then

      boom = 1

    end

  end

  return boom

end

local function gameLoop()

  local eps = 10

  local leftEdge = -60

  if gameStatus==1 then

    xLand = xLand + dt * uBird

    if xLand<0 then

      xLand = display.contentCenterX*2+xLand

    end

    land.x = xLand

    for i=1,3 do

      local xb = xBird-eps

      local xOld = pipes[i].x

      local x = xOld + dt * uBird

      if x<leftEdge then

        x = wPipe*3+x

        pipes[i].y =  calcRandomHole()

      end

      if xOld > xb  and x <= xb then

        score = score + 1

        title.text = score

        if score==scoreStep then

          scoreStep = scoreStep + 5

          audio.play( pointSound )

        end

      end

      pipes[i].x = x

      if collision(i)==1 then

        explosion()

        audio.play( dieSound )

        gameStatus = 2

      end

    end

  end

  if gameStatus==1 or gameStatus==2 then

    vBird = vBird + dt * g

    yBird = yBird + dt * vBird

    if yBird>yLand-eps then

      yBird = yLand-eps

      crash()

    end

    bird.x = xBird

    bird.y = yBird

    if gameStatus==1 then

      bird.rotation =  -30*math.atan(vBird/uBird)

    else

      bird.rotation = vBird/8

    end

  end

end

local function setupLand()

  land = display.newImageRect( “Assets/land.png”, display.actualContentWidth*2, hLand*2 )

  land.x = xLand

  land.y = yLand+hLand

end

local function setupImages()

  local ground = display.newImageRect( “Assets/ground.png”, display.actualContentWidth, display.actualContentHeight )

  ground.x = display.contentCenterX

  ground.y = display.contentCenterY

  ground:addEventListener(“tap”, wing)

  

  for i=1,3 do

    pipes[i] = display.newImageRect( “Assets/pipe.png”, 80, 1000 )

    pipes[i].x = 440 + wPipe * (i-1)

    pipes[i].y = calcRandomHole()

  end

  getReady = display.newImageRect( “Assets/getready.png”, 200, 60 )

  getReady.x = display.contentCenterX

  getReady.y = yReady

  getReady.alpha = 0

  gameOver = display.newImageRect( “Assets/gameover.png”, 200, 60 )

  gameOver.x = display.contentCenterX

  gameOver.y = 0

  gameOver.alpha = 0

  

  board = display.newGroup()

  local img = display.newImageRect(board, “Assets/board.png”, 240, 140 )

  scoreTitle = display.newText(board, score, 80, -18, “Assets/troika.otf”, 21)

  scoreTitle:setFillColor( 0.75, 0, 0 )

  bestTitle = display.newText(board, bestScore, 80, 24, “Assets/troika.otf”, 21)

  bestTitle:setFillColor( 0.75, 0, 0 )

  silver = display.newImageRect(board, “Assets/silver.png”, 44, 44 )

  silver.x = -64

  silver.y = 4

  gold = display.newImageRect(board, “Assets/gold.png”, 44, 44 )

  gold.x = -64

  gold.y = 4

  board.x = display.contentCenterX

  board.y = 0

  board.alpha = 0

  local txt = {

    x=display.contentCenterX, y=60,

    text="",

    font=“Assets/troika.otf”,

    fontSize=35 }

  title = display.newText(txt)

  title:setFillColor( 1, 1, 1 )

end

– Start application point

loadSounds()

setupImages()

setupBird()

setupExplosion()

setupLand()

initGame()

loadBestScore()

gameLoopTimer = timer.performWithDelay( 25, gameLoop, 0 )

– debug text line

– if you dont need debug line just comment all lines with loadingText 

local loadingText = display.newText( “Толик пидор”, display.contentCenterX, display.contentCenterY*1.9, nil, 17)

– appodeal listener

local function adListener( event )

    if ( event.phase == “init” ) then  – Successful initialization

        – maybe set a flag that you can see in all scenes to know that initialization is complete

    elseif ( event.phase == “failed” ) then  – The ad failed to load

        print( event.type )

        print( event.isError )

        print( event.response )

    end

end

display.setStatusBar( display.HiddenStatusBar )

appodeal.init( adListener,

      { appKey=“d0b151949cc7fdaecc358106bb00d606fdc7d51b70436d36”,

      locationTracking = false,

  supportedAdTypes = {“interstitial”},

        childDirectedTreatment = true,

  bannerAnimation = true,

  testMode = true } )

end

function scene:show( event )

local sceneGroup = self.view

local phase = event.phase

if phase == “will” then

– Called when the scene is still off screen and is about to move on screen

elseif phase == “did” then

– Called when the scene is now on screen

– 

– INSERT code here to make the scene come alive

– e.g. start timers, begin animation, play audio, etc.

end

end

function scene:hide( event )

local sceneGroup = self.view

local phase = event.phase

if event.phase == “will” then

– Called when the scene is on screen and is about to move off screen

– INSERT code here to pause the scene

– e.g. stop timers, stop animation, unload sounds, etc.)

elseif phase == “did” then

end

end

function scene:destroy( event )

– Called prior to the removal of scene’s “view” (sceneGroup)

– 

– INSERT code here to cleanup the scene

– e.g. remove display objects, remove touch listeners, save state, etc.

local sceneGroup = self.view

end


– Listener setup

scene:addEventListener( “create”, scene )

scene:addEventListener( “show”, scene )

scene:addEventListener( “hide”, scene )

scene:addEventListener( “destroy”, scene )


return scene

I don’t think you are going to get much help since you just dumped a lot of unformatted code in your message.

What error are you getting?

Looking very quickly, it looks like your entire scene’s code is placed in the create() function.

My guess is the reason why the scene was not removed is because you did not include insert the game objects in the sceneGroup group, and the way the code is written, you are not using Composer to manage your scene.

My suggestion is to read up on Composer, format the code using the code formatting button (the “<>” button) so it can be read, and only include the code that is needed to help troubleshoot.

Added this to my initGame() function, “ba” is printing in console, but scene doesn’t changing:

local ui = display.newGroup() local homeButton = display.newImageRect(ui, "Assets/button2.png", 256, 256) homeButton.x = 150 homeButton.y=150 homeButton:addEventListener( "touch", function(e) if e.phase=="began" then composer.gotoScene( "scenes.menu", composer.defaultOptions ) print("ba") end return true end )

sry, didnt know about <> function

I had the same question as @noobawok20. As @schizoid2k suggests, the answer is in the Composer documentation at https://docs.coronalabs.com/guide/system/composer/index.html#aboutscenes . I’m not sure what etiquette is on these forums, about posting links to documentation vs. parroting what’s in the documentation. I hope I don’t misstep here.

If I understand correctly, whenever you create an object that is supposed to be displayed in the scene, the object needs to be explicitly inserted in the sceneGroup in scene:create(), like this:

sceneGroup:insert( bird ) sceneGroup:insert( title ) sceneGroup:insert( et cetera )

If you don’t insert the object in the sceneGroup, it’s displayed on a layer above the sceneGroup, and it never goes away as long as the app is running. That defeats the entire purpose of creating a sceneGroup and using Composer.

I think I got that right. Experienced developers, please feel free to correct me.

You are right about that @ray6 but typically you want to add each and every display object to a display group. You then insert these display groups into the sceneGroup.

Typically the easiest approach is to create all display groups that you’ll need outside of the scene methods and then add all of the display groups to the sceneGroup at the bottom of scene:create() method. Then, whenever you create a new display object, you simply need to add it to its display group and everything will run smoothly.

Let me address several things. 

First, to the OP, one of the reasons we encourage asking questions here is that we have code formatting (the blue <> button). You can go back and edit your post, remove the hard-to-read code, and then paste it in after clicking <>. With out it, I can’t tell where you’re really doing anything.

Secondly, posting your entire scene is considered bad etiquette too. It’s just too much code. Usually developers can find a way to narrow down the problem to a smaller block of code and share that.

If you need to share more code than fits on one or two scrolls, you’re posting too much. You can always put your whole project, or a whole large file in a .zip file, upload it to a sharing service like DropBox, Google Drive, etc. and share the link here.

As for @ray6’s question about posting links to docs. That’s always a best practice. You can even copy/paste passages, or show snippits of code from the documentation… whatever you think will help the person with their question.

Now back to the OP’s original question…

With a quick glance, I don’t see where you’re putting your display object’s in the scene’s view group. If you want Composer to manage your scenes, you must do this. If not changing scenes will not remove the old scene’s objects.

Next, there are areas where you should place code and others where you should not. Lua is a one-pass compiler, so functions and variables have to be declared/created before you can use them, unlike a two-pass compiler like C. People coming from C declare their main function first and put other functions underneath. In Lua you have to do it the other way. Declare your functions above the scene:create() function and then call those functions from scene:create() or scene:show() as necessary. If this causes you errors, search the docs site and the blog for “scope” and learn all you can about it.

Next, scene:create() is a place to create your scene’s static objects. Spawning enemies or objects after the scene start will be initiated from scene:show() but should be in a function written somewhere above scene:create().

Finally it’s important to understand that “sceneGroup” is just a local pointer to the scene’s view group that’s only created as a convenience for you in the scene:create(), scene:show(), etc. functions. 

If functions outside of those, it’s “scene.view”. “scene.view” can be used any where. Another point of confusion is self.view. self is just a pointer to scene, so self.view = scene.view.  self.view can only be used inside of functions that start with scene: There are some good reasons why we use self.view inside those functions instead of scene.view, but for beginners it’s a complexity that causes more harm than good.

Rob