【cocos2dx 3.2】一个都不能死6 主场景层

来源:互联网 发布:c语言字符集转换 编辑:程序博客网 时间:2024/04/29 23:26

分析:

  1. 主场景中只需把任意数目的游戏层添加进来就好了
  2. 设置点击事件监听,点击后调用jump()方法
  3. 设置物理碰撞监听,碰撞后重新开始

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"#include "GameLayer.h"class HelloWorld : public cocos2d::LayerColor{public:      static cocos2d::Scene* createScene();virtual bool init();      CREATE_FUNC(HelloWorld);   void menuCloseCallback(cocos2d::Ref* pSender);    //把所有游戏层用向量存起来,以便管理Vector<GameLayer*> games;};#endif // __HELLOWORLD_SCENE_H__

HelloWorldScene.cpp

#include "HelloWorldScene.h"USING_NS_CC;Scene* HelloWorld::createScene(){    //创建物理场景auto scene = Scene::createWithPhysics();scene->getPhysicsWorld()->setGravity(Point(0,-1000));scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);        auto layer = HelloWorld::create();    scene->addChild(layer);    return scene;}bool HelloWorld::init(){    if ( !LayerColor::initWithColor(Color4B(255,140,0,255)))    {        return false;    }srand(time(NULL));    Size visibleSize = Director::getInstance()->getVisibleSize();    Point origin = Director::getInstance()->getVisibleOrigin();//添加游戏层,每层设置不同高度auto game = GameLayer::create(30);games.pushBack(game);addChild(game);auto game2 = GameLayer::create(200);games.pushBack(game2);addChild(game2);//设置点击监听事件auto listener = EventListenerTouchOneByOne::create();listener->onTouchBegan = [this](Touch *t,Event *e){for (auto it = games.begin(); it != games.end(); it++){if((*it)->getEdge()->getBoundingBox().containsPoint(t->getLocation())){(*it)->jump();}}return true;};Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);//设置物理碰撞监听事件auto contactListener = EventListenerPhysicsContact::create();contactListener->onContactBegin = [this](PhysicsContact &contact){for (auto i = games.begin(); i != games.end(); i++){(*i)->unscheduleUpdate();}Director::getInstance()->replaceScene(HelloWorld::createScene());return true;};Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener,this);return true;}    void HelloWorld::menuCloseCallback(Ref* pSender){#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");    return;#endif    Director::getInstance()->end();#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)    exit(0);#endif}


0 0
原创粉丝点击