Global是全局单类
唯一实例Single
Single.h
#ifndef _SINGLETON_H
#define _SINGLETON_H
using namespace std;
template <class T>
class Singleton
{
public:
//获取类的唯一实例
static inline T* instance();
//释放类的唯一实例
void release();
protected:
Singleton(void){}
~Singleton(void){}
static T* _instance;
};
template <class T>
inline T* Singleton<T>::instance()
{
if(NULL == _instance){
_instance = new T;
}
return _instance;
}
template <class T>
void Singleton<T>::release()
{
if (!_instance)
return;
delete _instance;
_instance = 0;
}
//cpp文件中需要先声明静态变量
#define DECLARE_SINGLETON_MEMBER(_Ty) \
template <> _Ty* Singleton<_Ty>::_instance = NULL;
#endif//_SINGLETON_H
全局类Global
我把后面需要用的都放进去了,头文件好说.
Global.h
#ifndef _GLOBAL_H_
#define _GLOBAL_H_
#include "cocos2d.h"
USING_NS_CC;
#include "Singleton.h"
#include "GameLayer.h"
#include "OperateLayer.h"
#include "StateLayer.h"
//需引入以下类,否则在这些类中访问单例对象会报错
class GameLayer;
class OperateLayer;
class StateLayer;
class Hero;
class Enemy;
//全局单例
class Global :public Singleton<Global>
{
public:
Global(void);
~Global(void);
//GameScene *gameScene;
GameLayer *gameLayer; //游戏层
OperateLayer *operateLayer; //操作层
StateLayer * stateLayer; //状态层
Hero *hero; //英雄
__Array *enemies; //敌人
TMXTiledMap *tileMap; //地图
Point tilePosFromLocation(Vec2 MovePoint, TMXTiledMap *map = NULL);//将point转换成地图GID的point
bool tileAllowMove(Vec2 MovePoint);
};
#define global Global::instance()
#endif
Global.cpp
#include "Global.h"
DECLARE_SINGLETON_MEMBER(Global);
Global::Global(void)
{
}
Global::~Global(void)
{
CC_SAFE_DELETE(gameLayer);
CC_SAFE_DELETE(operateLayer);
CC_SAFE_DELETE(stateLayer);
CC_SAFE_DELETE(hero);
CC_SAFE_DELETE(enemies);
//CC_SAFE_DELETE(tileMap);
gameLayer = NULL;
operateLayer= NULL;
stateLayer= NULL;
hero= NULL;
enemies= NULL;
tileMap= NULL;
}
Point Global::tilePosFromLocation(Point MovePoint, TMXTiledMap *map)
{
Point point = MovePoint - map->getPosition();
Point pointGID = Vec2::ZERO;
pointGID.x = (int) (point.x / map->getTileSize().width);
pointGID.y = (int) ((map->getMapSize().height * map->getTileSize().height - point.y) / map->getTileSize().height);
return pointGID;
}
bool Global::tileAllowMove(Point MovePoint)
{
TMXLayer *floor = global->tileMap->getLayer("Floor");
Point tileGid = tilePosFromLocation(MovePoint,global->tileMap);
auto allowpoint =floor->getTileGIDAt(tileGid);
if(0 == allowpoint)
{
return false;
}
return true;
}
在需要用到的地方注册他比如GameLayer中:
GameLayer.h
#include "Global.h"
根据Global.h中所定义的,在对应cpp中需要添加诸如
- .cpp
GameLayer::GameLayer()
{
global->gameLayer=this;
}
OperateLayer::OperateLayer()
{
global->operateLayer=this;
}
StateLayer::StateLayer()
{
global->stateLayer = this;
}
转载于:https://blog.51cto.com/libinqi456/1642280