popScene with Transition

What’s the issue?

When we want to push a new scene we can add a transition.
Director::getInstance()->pushScene(CCTransitionFade::create(0.5, fight));
Sadly when we use popScene the Scene is replaced without a transition.
Is it able to add a transition?

What’s the engine version?
3.0

Thanks in advance

I’ve subclassed Director to be able to do this. I did it originally for v2, but have ported it to v3. I’m happy to share the code:

CustomDirector.h

NS_CC_BEGIN
 
class CustomDirector : public Director
{
public:
    template&ltclass T&gt void popSceneWithTransition(float duration)
    {
        CCASSERT(_runningScene != NULL, "running scene should not null");
         
        _scenesStack.popBack();
        ssize_t c = _scenesStack.size();
         
        if (c == 0)
        {
            end();
        }
        else
        {
            Scene *scene = (Scene *)T::create(duration, (Scene *)_scenesStack.at(c-1));
            _scenesStack.replace(c-1, scene);
            _sendCleanupToScene = true;
            _nextScene = (Scene*)_scenesStack.at(c - 1);
        }
    }
};
 
NS_CC_END

To use, simply:

CustomDirector *director = (CustomDirector *)Director::getInstance();
director-&gtpopSceneWithTransition&ltTransitionSlideInR&gt(0.5);

You can, of course, replace “TransitionSlideInR” with any other builtin or custom transition you want.

I’ve tested my v2 code quite heavily, but this one, not as much… so there may be bugs.

1 Like

@toojuice
Thanks! :;ok

Thanks! Works perfect.

I have a similar solution

functions to insert in CCDirector.h

Scene* getPreviousScene() const 
{ 
	return _scenesStack.at(_scenesStack.size() - 2); 
}
void popAndReplace(Scene* s)
{
	_scenesStack.popBack();
	_sendCleanupToScene = true;
	_nextScene = s;
}
#define POP_SCENE_WITH_TRANSITION(_TYPE, d) Director::getInstance()->popAndReplace(_TYPE::create(d, Director::getInstance()->getPreviousScene()))

Usage
POP_SCENE_WITH_TRANSITION(TransitionSlideInL, 0.3f);

A word of warning thought. This is important to call this only after the previous transition is finished. I strongly recommend to add a test that the previous transition if finished before calling this, otherwise it may crash.

Here is my solution that has been working great so far without having to change any of the cocos2d sources: http://bit.ly/cocos-pop-transition-hpp

Instead of calling cocos2d::Director::getInstance()->popScene() just call:

cocos2d::Director::getInstance()->pushScene(
     pop_scene_with<cocos2d::TransitionFlipX>::create(1.0f, cocos2d::TransitionScene::Orientation::LEFT_OVER)
);

Note that there is no typical 2nd argument taking the scene for the transition, one simply passes all the arguments they would pass to the transition’s create method except for the 2nd argument carrying the scene.

1 Like