Cocos2d-x Series 6 Data Operations

Source: Internet
Author: User

I. Timer

In the cocos2d-x, similar to the Timer operation, there is no need to write Timer, in fact, in the Node element, has added the function of timed execution;

Let's take a look at the definition in Node.

// ...bool Node::isScheduled(SEL_SCHEDULE selector){    return _scheduler->isScheduled(selector, this);}void Node::scheduleUpdate(){    scheduleUpdateWithPriority(0);}void Node::scheduleUpdateWithPriority(int priority){    _scheduler->scheduleUpdate(this, priority, !_running);}// ...

The following is an example of mobile LabelTTF.

HelloWorldScene. h

# Ifndef _ HELLOWORLD_SCENE_H __# define _ HELLOWORLD_SCENE_H __# include "cocos2d. h "USING_NS_CC; class HelloWorld: public cocos2d: Layer {private: cocos2d: LabelTTF * label; public: static cocos2d: Scene * createScene (); virtual bool init (); CREATE_FUNC (HelloWorld); virtual void update (float dt); // 1> update method. In this method, perform the required void timerHandler (float dt) operations on a scheduled basis ); // 2> execute this method at a custom interval}; # endif/_ HELLOWORLD_SCENE_H __

HelloWorldScene. cpp

# Include "HelloWorldScene. h "# include <iostream> USING_NS_CC; using namespace cocos2d; Scene * HelloWorld: createScene () {auto scene = Scene: create (); auto layer = HelloWorld :: create (); scene-> addChild (layer); return scene;} bool HelloWorld: init () {// 1. super init first if (! Layer: init () {return false;} label = LabelTTF: create ("Move", "Courier", 30); addChild (label ); // scheduleUpdate (); 1> after this method is enabled, the update method is executed at each frame of the program running. You must specify the update method for implementation. schedule (schedule_selector (HelloWorld :: timerHandler), 1); // 2> execute the timerHandler method once every 1 s @ 1 return true;} void HelloWorld: update (float dt) {label-> setPosition (label-> getPosition () + Point (1, 1); if (label-> getPosition (). x> 500) {unscheduleUpdate (); // 1> stop loop execution update method} void HelloWorld: timerHandler (float dt) {//> 2 log (">>>>> ");}

@ 1 Let's take a look at the definition of the schedule method in Node. We can see that the first parameter of the schedule method is a SEL_SCHEDULE;

void Node::schedule(SEL_SCHEDULE selector){    this->schedule(selector, 0.0f, kRepeatForever, 0.0f);}void Node::schedule(SEL_SCHEDULE selector, float interval){    this->schedule(selector, interval, kRepeatForever, 0.0f);}void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay){    CCASSERT( selector, "Argument must be non-nil");    CCASSERT( interval >=0, "Argument must be positive");    _scheduler->schedule(selector, this, interval , repeat, delay, !_running);}

See SEL_SCHEDULE's definition:

typedef void (Ref::*SEL_SCHEDULE)(float);
#define schedule_selector(_SELECTOR) static_cast<cocos2d::SEL_SCHEDULE>(&_SELECTOR)

From this we can see that it is actually a c ++ function pointer, the parameter is float, and the return value is void (see the definition of the timerHandler function in HelloWorldScene. h );

The two timer types are described above. One is schedule and the other is scheduleUpdate. The other is that the time frequency cannot be specified, which is determined by the Frame Rate of the game;

Ii. preference settings

In cocos2d-x, preferences are similar to those in android;

    // UserDefault::getInstance()->setStringForKey("name", "Livingstone");    std::string s = UserDefault::getInstance()->getStringForKey("name1", "Hello World");    log("name=%s", s.c_str());

In the code above, a name string is saved and then read. Other data types can also be saved;

Iii. file read/write

In the cocos2d-x, file read and write is actually directly using c/c ++ in the file read and write operations method, but in the actual use, because the mobile client to read and write files need the corresponding permissions, so read and write files need to specify the path of the file, we do not need to obtain the absolute path, just need to obtain the relative path on the line, because the underlying cocos2d-x has done the corresponding processing of each platform;

FileUtils * fu = FileUtils: getInstance (); // log ("path = % s", fu-> getWritablePath (). c_str (); // FILE * f = fopen (fu-> fullPathFromRelativeFile ("data.txt", fu-> getWritablePath ()). c_str (), "w"); // fprintf (f, "Hello Livingstone"); // fclose (f ); write the file Data d = fu-> getDataFromFile (fu-> fullPathFromRelativeFile ("data.txt", fu-> getWritablePath (); log ("data = % s", d. getBytes ());

Iv. plist File Reading

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>    <key>name</key>    <string>Ls</string>    <key>isgirl</key>    <false/></dict></plist>

Above is a plist file;

    FileUtils * fu = FileUtils::getInstance();
ValueMap vm = fu-> getValueMapFromFile ("Info. plist "); log (" % s ", vm [" name "]. asString (). c_str (); // read string --> Ls bool bl = vm ["isgirl"]. asBool (); // read bool --> 0 log ("% d", bl );

If the plist file node is an array, you can also use ValueVector getValueVectorFromFile ("xx"); to read data;

V. xml file reading

    FileUtils * fu = FileUtils::getInstance();    auto doc = new tinyxml2::XMLDocument();    doc->Parse(fu->getStringFromFile("data.xml").c_str());    auto root = doc->RootElement();    for (auto e = root->FirstChildElement(); e; e = e->NextSiblingElement()) {        std::string str;        for (auto attr = e->FirstAttribute(); attr; attr = attr->Next()) {            str += attr->Name();            str += ":";            str += attr->Value();            str += ",";        }        log("%s", str.c_str());    }

Data. xml

<data>    <p name="zs" age="23"/>    <p name="ls" age="25"/></data>

The output content of the above Code is:

Cocos2d: name: zs, age: 23,
Cocos2d: name: ls, age: 25,

Note: You need to import the cosos2d-x library <tinyxml2/tinyxml2.h>

6. Reading JSON files

Let's take a look at a json: [{"name": "zs", "age": 23 },{ "name": "ls", "age": 25}]

Rapidjson: Document d; d. parse <0> (fu-> getStringFromFile ("dj. json "). c_str (); // 0 indicates the default parsing method; log ("% s", d [rapidjson: SizeType (0)] ["name"]. getString ());

Note: You need to import the cocos2d-x library <json/document. h>

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.