内容介绍:

6、数据操作
(1)、计时器
	schedule(schedule_selector(HelloWorld::testJ),1); //void HelloWorld::testJ(float f){}  每隔1秒执行下这个函数
(2)、用户首选项默认数据读写
	UserDefault::getInstance()->setStringForKey("data","hellow");
	UserDefault::getInstance()->getStringForKey("data","default");
(3)、文件读写
	auto fu = FileUtils::getInstance();
	FILE *f = fopen(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()).c_str(),"w");
	fprintf(f,"helloworldn");
	fclose(f);
	
	Data d = fu->getDataFromFile(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()).c_str());
	log("%s",d.getBytes());
(4)、读取plist文件
	FileUtils *fu = FileUtils::getInstance();
	ValueMap vm = fu->getValueMapFromFile("data.plist");
	log("%s",vm["name"].asString().c_str());
	【完整例子:】
	ValueMap levelinfo=FileUtils::getInstance()->getValueMapFromFile("level01.plist");
    ValueMap mapinfo=levelinfo["mapinfo"].asValueMap();
    ValueMap linfo=levelinfo["levelinfo"].asValueMap();
    CCLOG("level info=%s",mapinfo["mapfile"].asString().c_str());
    CCLOG("level info=%d",linfo["money"].asInt());
    ValueVector group=linfo["group"].asValueVector();
    CCLOG("一共有怪物波数%ld",group.size());
    for (int i=0; i<group.size(); i++) {
       long npccount= group.at(i).asValueVector().size();
        ValueVector nowgroup=group.at(i).asValueVector();
        for (int j=0; j<npccount; j++) {
            CCLOG("npc group %d type %d,hp %d",i+1,nowgroup.at(j).asValueMap()["npctype"].asInt()
                  ,nowgroup.at(j).asValueMap()["npchp"].asInt());
        }
    }
(5)、读取XML文件
	#include <tinyxml2/tinyxml2.h>
	auto doc = new tinyxml2::XMLDocument();
	doc->Parse(FileUtils::getInstance()->getStringFromFile("data.xml").c_str);
	auto root = doc->RootElement();
	for(auto e=root->FirstChildElement();e;e=e->NextSiblingElemeng()){
		std::string str;
		for(auto attr = e->FirstAttribute();attr;attr=e->Next()){
			str += attr->Name();
			str += ":";
			str += attr->value();
			str += ",";
		}
		log("%s",str.c_str());
	}
(6)、读取json文件
	#include <json/document.h>
	rapidjson::Document d;
	d.Parse<0>(FileUtils::getInstance()->getStringFromFile("date.json").c_str());
	log(%s",d[(int)0]["name"].GetString());

7、背景音乐和音效设置
#include "SimpleAudioEngine.h"


using namespace CocosDenshion;
SimpleAudioEngine::getInstance()->playBackgroundMusic("bg.mid");//加载播放背景音乐
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();//停止背景音乐
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();//恢复背景音乐
SimpleAudioEngine::getInstance()->playEffect("eat.wav");//添加音效

8、加载动画
auto cache = SpriteFrameCache::getInstance();
    
cache->addSpriteFramesWithFile("grossini_blue.plist");

     Vector<SpriteFrame*> animFrames(15);
	 char str[100];
    for(int i = 1; i <= 4; i++)
    {
        
sprintf(str, "grossini_blue_%02d.png",i);
        
auto frame = cache->getSpriteFrameByName(str);
        
animFrames.pushBack(frame);
   
 }

    
auto animation = Animation::createWithSpriteFrames(animFrames, 0.2f);
     
     auto flowSprite = Sprite::create();
    
flowSprite->runAction(RepeatForever::create(Animate::create(animation)));
    this->addChild(flowSprite);
    flowSprite->setPosition(ccp(200, 200));

手机横竖屏设置
1、android

AndroidManifest.xml文件中,

screenOrientation="landscape" 为横屏,

screenOrientation="portrait"为竖屏

2、iOS

- (NSUInteger) supportedInterfaceOrientations{ 
#ifdef __IPHONE_6_0 
    // 横屏显示 
    // return UIInterfaceOrientationMaskLandscape; 
    // 竖屏显示 
    return UIInterfaceOrientationMaskPortrait; 
#endif 
} 

设备屏幕分辨率自适应
 CCSize frameSize = glview->getFrameSize();

//这填写的就是一般你作为背景图片的那种图片的大小,适配的原理就是放到和缩小,而以什么为参照,当然就是

//以最大的那张图片为参照,什么图片最大,当然是背景图片了,以后美工做图的时候用的就是以下的这个尺寸

CCSize winSize=CCSize(480,320);

 //将宽和高做一个比,通过这个比,来具体的调整逻辑分辨率的大小

         float widthRate = frameSize.width/winSize.width;

         float heightRate = frameSize.height/winSize.height;

         //如果是if中的语句,说明逻辑的高度有点大了,就把逻辑的高缩小到和宽度一样的比率

        if (widthRate > heightRate)

        {
            //里边传入的前俩个参数就是逻辑分辨率的大小,也就是通过getWinSize()得到的大小

        	glview->setDesignResolutionSize(winSize.width,

                winSize.height*heightRate/widthRate, kResolutionNoBorder);

        }
        else
        {
        	glview->setDesignResolutionSize(winSize.width*widthRate/heightRate, winSize.height,

                kResolutionNoBorder);

        }


有关const成员、static成员、const static成员的初始化:

 

1、const成员:只能在构造函数后的初始化列表中初始化

2、static成员:初始化在类外,且不加static修饰

3、const static成员:类只有唯一一份拷贝,且数值不能改变。因此,可以在类中声明处初始化,也可以像static在类外初始化

 
项目移植到android平台 
1、在VS2012中吧代码调试没问题
2、使用ADT eclipse工具打开导入项目的proj.android到工具中
3、设置环境变量 android_sdk_root ant_root java_home ndk_root
4、解决android项目库的加载 E:feijiMyCppGamecocos2dcocosplatformandroidjavasrc 目录下的org拷贝到 proj.android E:feijiMyCppGameproj.androidsrc 目录下覆盖
5、解决eclipse中adriod的版本,右键属性项目 -》 android勾选android4.4->移除下面的library
6、在命令行进入项目的跟目录 执行: cocos compile -p android 进行项目编译




autoRelease、retain和release函数
1:那倒底什么时候要retain?
很简单,当你把一个对象让他作为成员变量时,并且没有把对象addChild到另外一个对象时,就需要调用retain函数。
Retain的意思是保持引用,也就是说,如果想保持某个对象的引用,避免它被Cocos2d-x释放,那就要调用对象的retain函数。
一旦调用对象的autoRelease函数,那么这个对象就被Cocos2d-x的内存管理机制给盯上了,如果这个对象没人认领,那就等着被释放吧
addChild函数就是导致大家混乱的凶手了,addChild函数会调用对象的retain函数,为什么它要调用对象的retain函数呢?因为你都把对象送给它当孩子了,它当然要认领这个对象了!





进度条:
Sprite *psSprite2 = Sprite::create("loadBar.png");
progresstime2 = CCProgressTimer::create(psSprite2);    //初始化CCProgressTimer
progresstime2->setType(ProgressTimer::Type::BAR);//设置类型
progresstime2->setMidpoint(Point(0, 0));//设置中心点,0.5,0.5是中间开始加  0,0从左边开始加  1,1从右边开始加
progresstime2->setBarChangeRate(Point(1, 0));//设置进度条的长度和高度开始变化的大小
progresstime2->setPercentage(0);//初始化进度条的值
progresstime2->setAnchorPoint(Point(0.5f, 0.5f));//设置进度条的锚点

schedule(schedule_selector(MapScene::gobar));
在计时器中改变进度条的值:progresstime2->setPercentage(i); 10 20 30 40 ...100

tiled地图的使用:
map = TMXTiledMap::create("map.tmx");//创建一个地图

//获得地图对象路径上的所有点
	TMXObjectGroup *group = map->objectGroupNamed("obj");
	std::vector<Point> path;
	int i = 1;
	while(true){
		char strp [3];
		sprintf(strp,"p%d",i);
		ValueMap  pointMap= group->objectNamed(strp);
		if(pointMap.empty())
			break;
		path.push_back(Point(pointMap.at("x").asFloat(),pointMap.at("y").asFloat()));
		i ++;
	}
Point point = t->getLocationInView()/32;//获得屏幕的坐标/32
point = Point((int)point.x,(int)point.y);//获得地图的坐标
TMXLayer *role = map->layerNamed("role");//获得地图上的layer
int gid = role->tileGIDAt(point);//获得该地图坐标上的gid
role->setTileGID(1,point);//设置该地图坐标上的GID,GID一旦改变地图坐标上的东西也改变