cocos2d-x-3.x 场景(2)简单切换场景
首先建立一个新的类,把它称作ImageScene,放在Classes之中
然后这里贴一下代码:
头文件:
1 ImageScene.h 2 3 #include <iostream> 4 #include <cocos2d.h> 5 USING_NS_CC; 6 7 class ImageScene :public Layer{ 8 public: 9 virtual bool init(); 10 static Scene* createScene(); 11 CREATE_FUNC(ImageScene); 12 };
CPP:
1 #include "ImageScene.h" 2 3 4 Scene* ImageScene::createScene(){ 5 6 Scene* scene = Scene::create(); 7 8 ImageScene * layer = ImageScene::create(); 9 scene -> addChild(layer); 10 return scene; 11 } 12 13 bool ImageScene::init(){ 14 Size size = Director::getInstance()->getVisibleSize(); 15 Sprite * s = Sprite::create("0840.png"); //此处()里的为切换后的图片场景文件 16 s->setPosition(size.width / 2, size.height / 2); //此处设置位置 17 addChild(s); 18 return true; 19 }
然后呢,在HelloWorldScene.cpp中,老样子找到位置,详见操作(1),该删除的删除掉。
然后添加代码段,这里展示添加完全的。
先介绍如何切换图片~轻轻点击就可以切换
1 bool HelloWorld::init() 2 { 3 4 if (!Layer::init()) 5 { 6 return false; 7 } 8 9 Size visibleSize = Director::getInstance()->getVisibleSize(); 10 Vec2 origin = Director::getInstance()->getVisibleOrigin(); 11 12 Sprite * label = Sprite::create("0842.png"); //设置前一个场景的图片,()里为图片文件名 13 label->setPosition(visibleSize.width/2,visibleSize.height/2); //设置位置 14 addChild(label); //加入图层 15 label->setPosition(visibleSize.width / 2, visibleSize.height / 2); 16 EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create(); 17 listener->onTouchBegan = [label](Touch *t, Event *e){ 18 if (label->getBoundingBox().containsPoint(t->getLocation())){ 19 Director::getInstance()->replaceScene(ImageScene::createScene()); 20 } 21 return false; 22 }; 23 Director::getInstance()->getEventDispatcher()-> 24 addEventListenerWithSceneGraphPriority(listener, label); 25 26 return true; 27 }
这里介绍如何由文字到图片切换
1 bool HelloWorld::init() 2 { 3 4 if (!Layer::init()) 5 { 6 return false; 7 } 8 9 Size visibleSize = Director::getInstance()->getVisibleSize(); 10 Vec2 origin = Director::getInstance()->getVisibleOrigin(); 11 12 LabelTTF *label = LabelTTF::create("show the next scene", "Andalus", 20); //设置显示文字,第二个为字体,随意选,第三个为字号。 13 addChild(label); //把这个加入图层 14 label->setPosition(visibleSize.width / 2, visibleSize.height / 2); 15 EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create(); 16 listener->onTouchBegan = [label](Touch *t, Event *e){ 17 if (label->getBoundingBox().containsPoint(t->getLocation())){ 18 Director::getInstance()->replaceScene(ImageScene::createScene()); 19 } 20 return false; 21 }; 22 Director::getInstance()->getEventDispatcher()-> 23 addEventListenerWithSceneGraphPriority(listener, label); 24 25 return true; 26 }
然后,至于其他的,比如文字转文字,图片转文字,稍微修改一下就可以了~