//GameScene.h
#include "cocos2d.h"
USING_NS_CC;
class GameScene : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
void menuCallback(Ref* pSender);
CREATE_FUNC(GameScene);
private: //注意不能用auto关键字
Size size;
Sprite *sprite;
};
//GameScene.cpp
// Created by Jacedy on 14-8-11.
#include "GameScene.h"
USING_NS_CC;
cocos2d::Scene* GameScene::createScene()
{
auto scene = Scene::create(); //创建一个场景
auto layer = GameScene::create(); //创建一个图层
scene->addChild(layer);
return scene;
}
//初始化当前的图层
bool GameScene::init()
{
if(!Layer::init()) //初始化父类
return false;
//获取屏幕大小
size = Director::getInstance()->getVisibleSize();
//auto size = Director::getInstance()->getWinSize();
//添加一个图片精灵
sprite = Sprite::create("OnePiece_1.png");
sprite->setPosition(Vec2(size.width/2, size.height/2));
this->addChild(sprite);
//新建数据
UserDefault::getInstance()->setBoolForKey("BOOL", true);
UserDefault::getInstance()->setFloatForKey("Float", 12.18);
UserDefault::getInstance()->setStringForKey("String", "Jacedy");
//保存数据
UserDefault::getInstance()->flush();
bool b = UserDefault::getInstance()->getBoolForKey("BOOL", false); //第二个参数为初始化内容
float f = UserDefault::getInstance()->getFloatForKey("Float", 0.0f);
std::string s = UserDefault::getInstance()->getStringForKey("String", "null");
//打印输出
log("b = %d", b);
log("f = %f", f);
log("s = %s", s.c_str());
//获取文件路径
//FileUtils::getInstance()->getWritablePath();
//判断XML文件是否存在
//UserDefault::getInstance()->isXMLFileExit();
return true;
}
void GameScene::menuCallback(Ref* pSender)
{
}
备注:使用UserDefault保存最高分、声音等一些数据,当用户结束了游戏重新打开时,如果使用 isXMLFileExit() 来判断XML文件是否存在,那么系统就会初始化XML文件,里面原来的数据也就清除了。所以不能用isXMLFileExit() ,解决办法:通过直接判断一个键值是否存在来获取XML文件数据,代码如下:
bool MenuLayer::init()
{
if(!Layer::init()) //初始化父类
return false;
size = Director::getInstance()->getVisibleSize();
//初始化最高分数
if(!UserDefault::getInstance()->getBoolForKey("isExit", false))
{
UserDefault::getInstance()->setBoolForKey("isExit",true);
m_bestscore = 0;
UserDefault::getInstance()->setIntegerForKey("m_bestscore", 0);
//第一次运行时,如果XML文件不存在就会新建
UserDefault::getInstance()->flush();
}
return true;
}