Use of common classes of cocos2d_x_03 _, cocos2d_x_03

Source: Internet
Author: User

Use of common classes of cocos2d_x_03 _, cocos2d_x_03
I. Use of TextFieldTTF input box

# Pragma mark-custom method // custom method, add a TextFieldvoid TextFieldScene: addOneTextField (float x, float y) {TextFieldTTF * field = TextFieldTTF :: textfieldwit2d-aceholder ("Enter:", "", 50); field-> setPosition (x, y); // Add the genie to the current Layer this-> addChild (field ); // 2. 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. field // () indicates the parameter listener-> onTouchBegan = [field] (Touch * t, Event * e) {// getLocation returns an OpenGL coordinate. // if the clicked vertex is in textField, if (field-> getBoundingBox () is allowed (). containsPoint (t-> getLocation () {field-> attachWithIME ();} else {field-> detachWithIME ();} return false ;}; // 3. Get the event distributor and add an event listener to this. That is, listen to the field object [text input box] Director: getInstance ()-> getEventDispatcher () -> addEventListenerWithSceneGraphPriority (listener, field );}


Ii. Custom class Ball, inherited from SpriteBall. h
CREATE_FUNC (type) Macro
Ball. cppinit method implementation
You can use a custom class in the home scenario to create an instance object either in the onEnter () method or in init () Method

3, Cocos2d-x memory management reference count recommended: when using, first retain, use release not recommended: delete simplified operation: After the creation is complete, use autorelease (); iv. Menu usage
Method 2: Set the callback function as a closure function. It belongs to the callback function type defined in the latest feature menu item of c ++ 11 as follows:

2nd Methods: Set the callback method for the menu item through the macro
CC_CALLBACK_1 macro
Callback method declaration in. h file
Implementation of callback methods in. cpp files
V. Use of TableView
Import the cocos2d-x extension header file containing CCTableView. h
Scenario inherited from datasouce and delegate
The following is the data source method declaration.
The following table view proxy Declaration
Instantiate a tableView
Complete header file for the entire scenario
Implementation of the entire scenario. cpp File
/// TableViewScene. cpp // 01_cocos2d-x // Created by beyond on 14-10-4. # include "TableViewScene. h "Scene * TableViewScene: createScene () {// 'Scene 'is automatically released // create a scene auto scene = scene: create (); // 'player' Automatically releases auto layer = TableViewScene: create (); // adds a layer to the scene-> addChild (layer ); // return scene for the scenario where the layer is filled;} // In the "init" method, instantiate the bool TableViewScene: init () {// 1. call the init of the parent class, cpp does not have s Uper, directly write the parent class name if (! Layer: init () return false; // screen size winSize = Director: getInstance ()-> getVisibleSize (); // Add a tableview Size = size (300,300); TableView * TV = TableView: create (this, Size); // set the TV-> setAnchorPoint (Point (0, 0); // set the position TV-> setPosition (winSize. width/2, winSize. height/2); // set the proxy TV-> setDelegate (this); // Add it to this addChild (TV); return true ;} # pragma mark-data source method // The following are all data source methods // total number of rows ssize_t TableViewScene: numberOfCellsInTableView (TableView * table) {return 7 ;} // Size of each row TableViewScene: tableCellSizeForIndex (TableView * table, ssize_t idx) {return Size (300, 60);} // cellTableViewCell * TableViewScene of each row :: tableCellAtIndex (TableView * table, ssize_t idx) {// reuse mechanism, which is obtained from the cache pool first and cannot be obtained before TableViewCell * cell = table-> dequeueCell (); LabelTTF * label; if (cell = NULL) {// create a cell = TableViewCell: create (); // create a new label = LabelTTF: create (); // bind the tag label-> setTag (5267); // set the font size label-> setFontSize (30); // set the anchorpoint label-> setAnchorPoint (Point (0, 0); // Add it to the cell-> addChild (label);} else {// directly retrieve the label in the cell and assign a new label = (LabelTTF *) cell-> getChildByTag (5267);} std: string arr [] = {"Baoyu", "Daiyu", "Baochai", "Xiangyun", "Spring ", "Miao Yu", "Qing Wen"}; // set the label content label-> setString (StringUtils: format ("Label % ld, % s", idx, arr [idx]. c_str (); // return the unique cell return cell;} # pragma mark-proxy method // The following are all proxy Methods // call void TableViewScene upon clicking :: tableCellTouched (TableView * table, TableViewCell * cell) {LabelTTF * label = (LabelTTF *) cell-> getChildByTag (5267); std: string content = StringUtils :: format ("n rows clicked, content: % s", label-> getString (). c_str (); MessageBox (content. c_str (), "title ");}


Focus:
StringUtils: format (); <span style = "color: rgb (57, 57, 57); font-family: 'courier new'; font-size: 24px; line-height: 32px; background-color: rgb (245,245,245); "> <strong> method </strong> </span>
<Span style = "color: rgb (57, 57, 57); font-family: 'courier new'; font-size: 24px; line-height: 32px; background-color: rgb (245,245,245); "> <strong> the returned std: string object can be passed through c_str () </strong> </span> <span style = "font-family: 'courier new'; background-color: rgb (245,245,245 ); "> convert the method to a c string </span>

Focus: reuse mechanism
TableCellTouched is equivalent to didSlectedRowAtIndexPath in iOS
6. Scenario Switching
:
Scenario. h header file
The scenario. cpp class adds a LabelTTF with a blank string, listens to click events, and switches the scenario.

VII. Action

// Create a listener object auto listener = EventListenerTouchOneByOne: create (); // The listener method uses the closure function to implement listener-> onTouchBegan = [label] (Touch * t, event * e) {// only when the clicked position is on the label, the listener Event if (label-> getBoundingBox () is returned (). containsPoint (t-> getLocation () {// absolute, relative label-> runAction (MoveTo: create (1, Point (100,100 ))); label-> runAction (MoveBy: create (1, Point (-50,-50)-> reverse ()); // concurrently execute the Spawn label-> runAction (Spawn: create (MoveBy: create (1, Point (100,100), RotateBy: create (1,360 ), NULL); label-> runAction (Sequence: create (MoveBy: create (1, Point (100,100), RotateBy: create (1,360), NULL )); // sequentially execute the Sequence label-> runAction (Sequence: create (MoveBy: create (1, Point (100,100), RotateBy: create (1,360 ), // closure function to implement the Action listening CallFunc: create ([] () {// when the Action is completed, the MessageBox ("Action complete ", "title") ;}, NULL) ;}return false ;}; // register an event listener with the event distributor to listen for the event Director ctor that occurs on the label :: getInstance ()-> getEventDispatcher ()-> addEventListenerWithSceneGraphPriority (listener, label );


8. frame-by-frame animation
First, 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

/// FrameAnimateScene. cpp // 01_cocos2d-x // Created by beyond on 14-10-4. //// # include "FrameAnimateScene. h "USING_NS_CC; Scene * FrameAnimateScene: createScene () {// 'Scene 'is automatically released // create a scene auto scene = scene: create (); // 'player' Automatically releases auto layer = FrameAnimateScene: create (); // adds a layer to the scene-> addChild (layer ); // return the scene of filling the layer: return scene;} // in the "init" method, instantiate the genie object bool FrameAnimateScene: in It () {// 1. Call the init of the parent class. cpp does not have super. directly write the parent class name if (! Layer: init () return false; // screen size winSize = Director: getInstance ()-> getVisibleSize (); // 2. add an Genie and play the Frame Animation this-> addSpriteFrameAniamtion (); return true ;}# pragma mark-custom method // 2. add an Genie and play the Frame Animation void FrameAnimateScene: addSpriteFrameAniamtion () {// spritframe cache Singleton auto cache = SpriteFrameCache: getInstance (); // The [sprite frame cache] will be based on the key in plist to the large texture album, cut and load small Sprite frames, and put into the frame cache. Later, you only need to follow the title of the thumbnail, you can retrieve the elf frame from the [genie frame cache] To cache-> addSpriteFramesWithFile ("anim. plist "); // container, array, which stores the sprite frame Vector <SpriteFrame *> vec; // The image name used to generate the elf frame. char name [15]; // use 0 to clear the memory memset (name, 0, 15); // extract all the elf frames from the frame cache and put them in the Vector for (int I = 0; I <20; I ++) {// format name, % 04d, indicating that less than four digits are filled with sprintf (name, "anim % 04d", I ); // Add the elf frame to the container vec. pushBack (cache-> Animation (name);} // Create Animation animation * Animation = Animation: createWithSpriteFrames (vec, 0.1f); // create Animate * animate = Animate:: create (animation); // create the sprite auto Sprite = sprite: create (); // Add it to this addChild (sprite ); // set the position sprite-> setPosition (200,200); // execute the Sequence Frame Animation Sequence * seq = Sequence: create (animate, animate-> reverse (), NULL ); sprite-> runAction (RepeatForever: create (seq ));}


9. In the event passing listener-> onTouchBegan method, the returned bool value determines whether the onTouchMove method can be triggered. OnTouchBegan method, return value is bool, parameter: Touch *, Event *
In the Event * e parameter, e-> getCurrentTarget obtains the clicked object, that is, when the listener is registered in the Event distributor, the bound Node object can listen to the Event as long as it is a Node.







How to Create a CCSprite-inherited class for cocos2d game development and use this class in projects

Create a new file and select CCNode class-based
Then select subclass of CCSprite, And the created class is based on CCSprite. You can directly use this class in the project.
Hope to help you.

In the cocos2d-x, how can we determine which type of class is given? For example, a CCObject can be CCString, CCArray, etc.

Strcmp (typeid (??? ). Name (), "class cocos2d: CCSprite *")

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.