Cocos2d_x_04 _ timer _ data storage, cocos2d_x_04 Timer

Source: Internet
Author: User

Cocos2d_x_04 _ timer _ data storage, cocos2d_x_04 Timer
I. Timer usage: Click the screen and move the Avatar to the specified position to stop the timer.
The type of SEL_SCHEDULE is actually a function pointer pointing to a member method of Ref,Float parameter, return value void
Scenario. h header file
Key code of the scenario class. cpp file:

//// UpdateScene. cpp // 01_cocos2d-x // Created by beyond on 14-10-5. //// # include "UpdateScene. h "USING_NS_CC; Scene * UpdateScene: createScene () {// 'Scene 'is automatically released // create a scene auto scene = scene: create (); // 'player' Automatically releases auto layer = UpdateScene: create (); // adds a layer to the scene-> addChild (layer ); // return the scenario of filling the layer: return scene;} // In the "init" method, instantiate the bool UpdateScene: init () {// 1. call the init of the parent class. cpp does not Super, directly write the parent class name if (! Layer: init () return false; // screen size winSize = Director: getInstance ()-> getVisibleSize (); // Add a genie and click the screen, in the update method, change the position addSprite (); // Add a LabelTTF, click the text, and change the position addLabelTTF (); return true;} in the updatePosition method ;} # pragma mark-Initialize // Add a genie. Click the screen and change the location void UpdateScene: addSprite () {// genie Nana nana = Sprite :: create ("nanaLogo.png"); nana-> setAnchorPoint (Point (0, 0); nana-> setPosition (Point (0, 0); this-> addChild (nana ); // 2. touch the screen to enable clock update. // instantiate a touch listener object auto listener = EventListenerTouchOneByOne: create (); // bind a closure function when the touch starts; // [] indicates the external object to be passed in. this // () indicates the parameter listener-> onTouchBegan = [this] (Touch * t, Event * e) {// enable the default clock method scheduleUpdate (); return false ;}; // 5. Obtain the event distributor and add an event listener to this; that is, the listener is the this object [entire Layer] ctor: getInstance ()-> getEventDispatcher ()-> addEventListenerWithSceneGraphPriority (listener, this);} // Add a LabelTTF, click the text and change the position void UpdateScene: addLabelTTF () {// Label label = LabelTTF: create ("Nana", "Courier", 90) in the updatePosition method ); label-> setAnchorPoint (Point (0, 0); label-> setPosition (Point (0, 0); label-> setName ("label"); addChild (label ); // 2. touch the Label to enable the clock updatePosition // instantiate a touch listener object auto listener = EventListenerTouchOneByOne: create (); // bind a closure function when the touch starts; // [] indicates the external object to be passed in. this // () indicates the parameter listener-> onTouchBegan = [this] (Touch * t, Event * e) {// If a label is clicked, the update location method LabelTTF * label = (LabelTTF *) e-> getCurrentTarget ()-> getChildByName ("label") is executed every second "); if (label-> getBoundingBox (). containsPoint (t-> getLocation () {// enable the clock method at the specified time. The parameter is a function pointer. the return value is void and the parameter is float, point to a method schedule (schedule_selector (UpdateScene: updatePosition), 1) ;}return false ;}; // 5. Obtain the event distributor, add an event listener to this, that is, listening to this object [entire Layer] ctor: getInstance ()-> getEventDispatcher ()-> addEventListenerWithSceneGraphPriority (listener, this) ;}# pragma mark-clock method // The clock method, which uses the default frame rate of 1/60 void UpdateScene: update (float dt) {// to the upper right corner, move nana. When the position is greater than 400, stop nana-> setPosition (nana-> getPosition () + Point (); if (nana-> getPosition (). x> 400) {// Method for stopping the clock unscheduleUpdate () ;}}// the method for stopping the clock. The void UpdateScene: updatePosition (float dt) is used once per second) {// move nana to the upper right corner. When the position is greater than 400, stop label-> setPosition (label-> getPosition () + Point (50, 50 )); if (label-> getPosition (). x> 300) {// stop all clock Methods unscheduleAllSelectors ();}}


Ii. user preference UserDefault

3. FileUtils file operation tool class it shields mac ios android and other platforms

FileUtils file writing and reading: if it is a Mac platform, the available Directory is: [/Users/beyond /Documents/] For iOS platform, the available Directory is: [.../app /Documents/ ]

Iv. Plist File Reading
The FileUtils tool class is still used.
The returned type is [ValueMap] or an array [ValueVector]
V. XML file reading



Library Used for parsing XML in cocos2d

# Include <tinyxml2/tinyxml2.h>



6. Reading JSON files

Cocos2d built-in Json Parsing Library

# Include <json/rapidjson. h>

# Include <json/document. h>


Mark parseFlags as 0 by default.

Output result:
VII. Scenario code implementation
//// FileScene. h // 01_cocos2d-x // Created by beyond on 14-10-5. /// # ifndef ___ character cocos2d_x _ FileScene __# define ___ character cocos2d_x _ FileScene __# include "cocos2d. h "USING_NS_CC; // note that Layerclass FileScene: public cocos2d: Layer {private: // screen Size winSize; Sprite * nana; LabelTTF * label; public: // c ++ does not have the id type, so the pointer to the Instance Object of the returned class is static cocos2d: Scene * createScene (); // The following are differences: the 'init 'method of the cocos2d-x returns bool // while the cocos2d-iphone returns the 'id' type virtual bool init (); // The macro automatically implements "static create () method "CREATE_FUNC (FileScene); // File operation // user preference void userDefault (); // File read/write FileUtils tool class, blocked void fileUtils () for mac ios android and other operating systems; // Plist returns only the dictionary [ValueMap] Or array [ValueVector] void readPlist (); // Parse XML void readXML (); // parse JSON void readJSON () ;};# endif/* defined (___ encode cocos2d_x _ FileScene __)*/


//// FileScene. cpp // 01_cocos2d-x // Created by beyond on 14-10-5. //// # include "FileScene. h "// import xml Parser # include <tinyxml2/tinyxml2.h> // import Json parser # include <json/rapidjson. h> # include <json/document. h> USING_NS_CC; Scene * FileScene: createScene () {// 'Scene 'is automatically released // create a scene auto scene = scene: create (); // 'player' Automatically releases auto layer = FileScene: create (); // adds a layer to scene in the scene-> addChild (layer); // return Return scene;} // In the "init" method, instantiate the bool FileScene: init () {// 1. call the init of the parent class. if (! Layer: init () return false; // screen size winSize = Director: getInstance ()-> getVisibleSize (); // 2. file Operation demonstration this-> userDefault (); this-> fileUtils (); this-> readPlist (); this-> readXML (); this-> readJSON (); return true ;}# pragma mark-file operation // user preference void FileScene: userDefault () {// save UserDefault: getInstance ()-> setStringForKey ("BookName ", "Dream of Red Mansions"); // read parameter 2 indicates: if the key is incorrect or the value cannot be obtained, the default value is log ("% s", UserDefault: getInstanc E ()-> getStringForKey ("BookName", "masterpiece "). c_str (); // cocos2d: Dream of Red Mansions} // FileUtils tool class for reading and writing files, shielding void FileScene: fileUtils () for mac ios android and other operating systems () *************** * ******* // 1. shielding file tools on different platforms [Singleton] auto util = FileUtils: getInstance (); // obtain the Writable Path. The returned value is std: string type std :: string wPath = util-> getWritablePath (); log ("wPath % s", wPath. c_str (); // cocos2d: wPath/Users/beyond/Library/ Pplication Support/iPhone Simulator/7.1/Applications/FC92FA39-E149-4C04-AC55-2FB0930E208B/Documents // file name + Relative Path = absolute path of the file std: string fullPath = util-> fullPathFromRelativeFile ("1.txt ", wPath); log ("fullPath % s", fullPath. c_str (); // cocos2d: fullPath/Users/beyond/Library/Application Support/iPhone Simulator/7.1/Applications/FC92FA39-E149-4C04-AC55-2FB0930E208B/Documents/1.txt // C file operation function parameter 1: file absolutely For path (C string), parameter 2: operation mode FILE * file = fopen (fullPath. c_str (), "w"); // 2. fprintf (file, "Demo: How to Write Hello Beyond ~ to different platforms through FileUtils ~ \ N "); // 3. close FILE fclose (file ); *************** * ***** Data d = util-> getDataFromFile (fullPath ); // output to the console log ("% s", d. getBytes (); // cocos2d: Demo: How to Write Hello Beyond ~} to different platforms through FileUtils ~} // Plist returns the dictionary [ValueMap] Or array [ValueVector] void FileScene: readPlist () {// 1. shielding file tools on different platforms [Singleton] FileUtils * util = FileUtils: getInstance (); // 2. the root is the dictionary ValueMap dict = util-> getValueMapFromFile ("data. plist "); // The ValueMap overload operator [] log (" % s ", dict [" name "]. asString (). c_str (); // cocos2d: std: string s = dict. at ("author "). asString (); log ("% s", s. c_str (); // cocos2d: Cao Xueqin} // Parse XML // import xml Parser // # I Nclude <tinyxml2/tinyxml2.h> void FileScene: readXML () {// Document Object tinyxml2: XMLDocument * doc = new tinyxml2: XMLDocument (); // 1. shielding file tools on different platforms [Singleton] FileUtils * util = FileUtils: getInstance (); std: string content = util-> getStringFromFile ("data. xml "); log (" % s ", content. c_str (); // 2. start parsing doc-> Parse (content. c_str (); // after the resolution is complete, obtain the root node tinyxml2: XMLElement * root = doc-> RootElement () from the doc; // obtain the [Fir StChildElement: Start By traversing all xmlelements until the node is empty for (tinyxml2: XMLElement * e = root-> FirstChildElement (); e! = NULL; e = e-> NextSiblingElement () {// used to concatenate std: string str; // Layer 4 traversal, traverse all attributes of a node for (auto attr = e-> FirstAttribute (); attr! = NULL; attr = attr-> Next () {// attribute Name str + = attr-> Name (); str + = ":"; // attribute Value str + = attr-> Value (); str + = "," ;}// output to the console log ("% s", str. c_str () ;}/// parse Json // # include <json/rapidjson. h> // # include <json/document. h> void FileScene: readJSON () {// Document Object rapidjson: Document doc; // 1. shielding file tools on different platforms [Singleton] FileUtils * util = FileUtils: getInstance (); std: string content = util-> getStringFromFile ("data. json "); log (" % s ", content. c_str (); // parse doc from a read-only string. parse <0> (content. c_str (); // after parsing, print the output int I = 0; log ("% s", doc [I] ["name"]. getString (); log ("% s", doc [I] ["author"]. getString (); log ("% s", doc [(int) 1] ["name"]. getString (); log ("% s", doc [(int) 1] ["author"]. getString ());}


8, Plist files and large images exported through Flash CC, Create Frame AnimationFirst, download flash_professional_13_ls1_dmg and run the patch about 1 GB.
Open Flash, open 【 Library], Click the new button in the lower left corner to create a new Symbol, and select [video Clip Movie Clip] As the type. draw a square in 1st frames and press F6 to create a key frame in 20th frames; delete the original square from the second frame and draw a circle. Right-click any frame between the two key frames and create a [deformation compensation animation shape tween, focus: export the large texture + Plist file used for cocos2d, click the library, right-click the created video clip movie clip, and select Generate Sprite Sheet ], select cocos2D v3 for data format and Export. A plist file and a large texture image are generated, as shown below:
Plist File
Relationship among SpriteBatchNode, texture cache, and SpriteBatchNode

9. Create a frame animation large image texture for the Json file and large image exported through Flash CC, as shown in:
The exported Json data is as follows:
{"frames": {"hero0000":{"frame": {"x":0,"y":0,"w":44,"h":52},"rotated": false,"trimmed": false,"spriteSourceSize": {"x":0,"y":0,"w":44,"h":52},"sourceSize": {"w":44,"h":52}},"hero0004":{"frame": {"x":42,"y":52,"w":42,"h":52},"rotated": false,"trimmed": true,"spriteSourceSize": {"x":2,"y":0,"w":44,"h":52},"sourceSize": {"w":44,"h":52}}},"meta": {"app": "Adobe Flash Professional","version": "13.1.0.226","image": "Hero.png","format": "RGBA8888","size": {"w":128,"h":128},"scale": "1"}}


The following code uses the built-in rapidJson parsing in cocos2d and encapsulates it into an Animate object (runAction can be directly used)
//// FlashTool. cpp // 01_cocos2d-x // Created by beyond on 14-10-6. //// # include "FlashTool. h "// Json parsing using the cocos2d built-in rapidJson library # include <json/document. h> // parse the Json file + large image exported by flash cc to generate an animation object for executing the sequential Frame Animation Animate * FlashTool: animateFromJsonFile (std: string jsonFile, float delayPerUnit) {// The Document Object rapidjson: Document doc; // The FileUtils tool class reads the json file std: string fileContent = FileUtils: getInstance ()-> ge TStringFromFile (jsonFile); // fileContent. erase (0, fileContent. find_first_of ('{'); // mark 0 by default and start parsing doc. parse <0> (fileContent. c_str (); // obtain the image name std: string imgFileName = doc ["meta"] ["image"]. getString (); auto & frames = doc ["frames"]; // The auto sfc = SpriteFrameCache: getInstance (); // The container is used to store all animation frames. The Vector <AnimationFrame *> animFrames; // traverses, crops, creates, and adds the Vector to the container for (auto m = frames. memberonBegin (); M! = Frames. memberonEnd (); m ++) {auto frameName = m-> name. getString (); auto & frameProperties = m-> value ["frame"]; auto & spriteSourceSize = m-> value ["spriteSourceSize"]; auto sf = sfc-> getSpriteFrameByName (frameName); if (! Sf) {sf = SpriteFrame: create (imgFileName, Rect (frameProperties ["x"]. getInt (), frameProperties ["y"]. getInt (), frameProperties ["w"]. getInt (), frameProperties ["h"]. getInt (), m-> value ["rotated"]. getBool (), Vec2 (spriteSourceSize ["x"]. getInt (), spriteSourceSize ["y"]. getInt (), Size (spriteSourceSize ["w"]. getInt (), spriteSourceSize ["h"]. getInt (); sfc-> addSpriteFrame (sf, frameName);} animFrames. pushBack (AnimationFrame: create (sf, delayPerUnit, ValueMapNull);} // generates the Animate Animation * animation = Animation: create (animFrames, delayPerUnit) for Action; return Animate:: create (animation );}











How does delphi7 save input timer data?

I'm not sure what you want to ask ????

Hitting timer Data Processing

Uniformly accelerated linear motion
Object velocity at different time points
V1: V2: V3. ......: Vn = ......: n
Object displacement in Ts at the same time interval
S1: S2: S3:...: Sn = ...... :( 2n-1)

Related Article

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.