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

分析:

  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
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值