diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index f921768aa9..cee03e61ac 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -518,6 +518,13 @@ void Node::setShaderProgram(GLProgram *pShaderProgram) _shaderProgram = pShaderProgram; } +Scene* Node::getScene() +{ + if(!_parent) + return nullptr; + return _parent->getScene(); +} + Rect Node::getBoundingBox() const { Rect rect = Rect(0, 0, _contentSize.width, _contentSize.height); diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 00168db336..c04c5c8fbe 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -53,6 +53,7 @@ class ActionManager; class Component; class ComponentContainer; class EventDispatcher; +class Scene; #ifdef CC_USE_PHYSICS class PhysicsBody; #endif @@ -910,6 +911,11 @@ public: */ virtual void visit(); + /** Returns the Scene that contains the Node. + It returns `nullptr` if the node doesn't belong to any Scene. + This function recursively calls parent->getScene() until parent is a Scene object. The results are not cached. It is that the user caches the results in case this functions is being used inside a loop. + */ + virtual Scene* getScene(); /** * Returns a "local" axis aligned bounding box of the node. diff --git a/cocos/2d/CCScene.cpp b/cocos/2d/CCScene.cpp index b6116b8d4f..37b653aad9 100644 --- a/cocos/2d/CCScene.cpp +++ b/cocos/2d/CCScene.cpp @@ -83,6 +83,11 @@ std::string Scene::getDescription() const return StringUtils::format("", _tag); } +Scene* Scene::getScene() +{ + return this; +} + #ifdef CC_USE_PHYSICS Scene *Scene::createWithPhysics() { diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 7f8462ccb5..12c0fa1dea 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -56,6 +56,8 @@ public: static Scene *createWithPhysics(); #endif + // Overrides + virtual Scene *getScene() override; #ifdef CC_USE_PHYSICS public: @@ -76,6 +78,7 @@ protected: #endif // CC_USE_PHYSICS + protected: Scene(); virtual ~Scene();