Scenes

This page will cover how to use scenes.

As mentioned in the section Cocos Basics scenes are ordered on a stack which is LIFO (Last In First Out). Take a look at the diagram below to help understand this concept

2000

Push and Pop Stack

Scene can be created either in the same file as an existing scene or a new code file. It is recommended to abstract as much as you can from a scene so it is easier to manage and debug. The following topics will be covered in this section:

Creating a new scene

#ifndef __NEW_SCENE_H__
#define __NEW_SCENE_H__

#include "cocos2d.h"

class NewScene : public cocos2d::Layer
{
public:
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene( );

    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init( );
    
    // a selector callback
    void menuCloseCallback( cocos2d::Ref* pSender );
    
    // implement the "static create()" method manually
    CREATE_FUNC( NewScene );
    
};

#endif // __NEW_SCENE_H__
#include "NewScene.h"

USING_NS_CC;

Scene* NewScene::createScene( )
{
    // 'scene' is an autorelease object
    auto scene = Scene::create( );
    
    // 'layer' is an autorelease object
    auto layer = NewScene::create( );

    // add layer as a child to scene
    scene->addChild( layer );

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool NewScene::init( )
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init( ) )
    {
        return false;
    }
    
    return true;
}
var NewSceneLayer = cc.Layer.extend(
{
    ctor:function( )
  	{
        //////////////////////////////
        // 1. super init first
        this._super( );

        return true;
    }
} );

var NewScene = cc.Scene.extend(
{
    onEnter:function( )
  	{
        this._super( );

        var layer = new NewSceneLayer( );
        this.addChild( layer );
    }
} );

Note: When adding a new file in Cocos2d-JS update the project.json to reflect this addition.

Running a scene - should only be used once to run a scene at the start of the game (Cocos runs a scene itself by default)

Scene *scene = NewScene::createScene( );
    
Director::getInstance( )->runWithScene( scene );
var scene = new NewScene( );

cc.director.runScene( scene );

Pushing a scene onto the stack

Scene *scene = NewScene::createScene( );
    
Director::getInstance( )->pushScene( scene );
var scene = new NewScene( );

cc.director.pushScene( scene );

Popping a scene off the stack

Director::getInstance( )->popScene( );
cc.director.popScene( );

Replacing a scene

auto scene = NewScene::createScene( );
    
Director::getInstance()->replaceScene( scene );
var scene = new NewScene( );

cc.director.runScene( scene );