加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2dx 适合初学者的学习笔记【三】

发布时间:2020-12-14 21:10:27 所属栏目:百科 来源:网络整理
导读:内容介绍: 6、数据操作(1)、计时器schedule(schedule_selector(HelloWorld::testJ),1);//voidHelloWorld::testJ(floatf){}每隔1秒执行下这个函数(2)、用户首选项默认数据读写UserDefault::getInstance()-setStringForKey("data","hellow");UserDefault::get

内容介绍:

6、数据操作
(1)、计时器
	schedule(schedule_selector(HelloWorld::testJ),1);//voidHelloWorld::testJ(floatf){}每隔1秒执行下这个函数
(2)、用户首选项默认数据读写
	UserDefault::getInstance()->setStringForKey("data","hellow");
	UserDefault::getInstance()->getStringForKey("data","default");
(3)、文件读写
	autofu=FileUtils::getInstance();
	FILE*f=fopen(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()).c_str(),"w");
	fprintf(f,"helloworldn");
	fclose(f);
	
	Datad=fu->getDataFromFile(fu->fullPathFromRelativeFile("data.txt",fu->getWritablePath()).c_str());
	log("%s",d.getBytes());
(4)、读取plist文件
	FileUtils*fu=FileUtils::getInstance();
	ValueMapvm=fu->getValueMapFromFile("data.plist");
	log("%s",vm["name"].asString().c_str());
	【完整例子:】
	ValueMaplevelinfo=FileUtils::getInstance()->getValueMapFromFile("level01.plist");
ValueMapmapinfo=levelinfo["mapinfo"].asValueMap();
ValueMaplinfo=levelinfo["levelinfo"].asValueMap();
CCLOG("levelinfo=%s",mapinfo["mapfile"].asString().c_str());
CCLOG("levelinfo=%d",linfo["money"].asInt());
ValueVectorgroup=linfo["group"].asValueVector();
CCLOG("一共有怪物波数%ld",group.size());
for(inti=0;i<group.size();i++){
longnpccount=group.at(i).asValueVector().size();
ValueVectornowgroup=group.at(i).asValueVector();
for(intj=0;j<npccount;j++){
CCLOG("npcgroup%dtype%d,hp%d",i+1,nowgroup.at(j).asValueMap()["npctype"].asInt(),nowgroup.at(j).asValueMap()["npchp"].asInt());
}
}
(5)、读取XML文件
	#include<tinyxml2/tinyxml2.h>
	autodoc=newtinyxml2::XMLDocument();
	doc->Parse(FileUtils::getInstance()->getStringFromFile("data.xml").c_str);
	autoroot=doc->RootElement();
	for(autoe=root->FirstChildElement();e;e=e->NextSiblingElemeng()){
		std::stringstr;
		for(autoattr=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::Documentd;
	d.Parse<0>(FileUtils::getInstance()->getStringFromFile("date.json").c_str());
	log(%s",d[(int)0]["name"].GetString());

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


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

8、加载动画
autocache=SpriteFrameCache::getInstance();

cache->addSpriteFramesWithFile("grossini_blue.plist");

Vector<SpriteFrame*>animFrames(15);
	charstr[100];
for(inti=1;i<=4;i++)
{

sprintf(str,"grossini_blue_%02d.png",i);

autoframe=cache->getSpriteFrameByName(str);

animFrames.pushBack(frame);

}


autoanimation=Animation::createWithSpriteFrames(animFrames,0.2f);

autoflowSprite=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
//横屏显示
//returnUIInterfaceOrientationMaskLandscape;
//竖屏显示
returnUIInterfaceOrientationMaskPortrait;
#endif
}

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

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

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

CCSizewinSize=CCSize(480,320);

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

floatwidthRate=frameSize.width/winSize.width;

floatheightRate=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成员、conststatic成员的初始化:



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

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

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


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




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);10203040...100

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读