Introduction of _ Array container and instance in Cocos2d-x, cocos2d-x _ array

Source: Internet
Author: User

Introduction of _ Array container and instance in Cocos2d-x, cocos2d-x _ array
_ Array class in the era of Cocos2d-x 2. x It is a CCArray class. It is designed to mimic the NSArray class in Objective-C and manage the memory by referencing the count. _ Array inherits from the Ref class, so it can accommodate the Ref and the Object Pointer created by the subclass.


1. Create an _ Array object
There are many functions to create the _ Array object. The following is a summary of common functions:
Static _ Array * create (). Create _ Array.
Static _ Array * create (Ref * object ,...). Use a series of Ref to create _ Array.
Static _ Array * createWithObject (Ref * object ). Use a Ref to create _ Array.
Static _ Array * createWithCapacity (unsigned int capacity ). Create _ Array and set the capacity.
Static _ Array * createWith _ Array (_ Array * other _ Array ). Use an existing _ Array to create another _ Array.
Static _ Array * createWithContentsOfFile (const std: string & pFileName ). Create _ Array from the property list file.


2. Add Elements
Add elements to the _ Array object must be the object pointer type of the Ref and its subclass. The following is a summary of common functions:
Void addObject (Ref * object ). Add an element.
Void addObjectsFromArray (_ Array * otherArray ). Add all the elements in a _ Array object to the current _ Array object.
Void insertObject (Ref * object, ssize_t index ). Insert an element at the specified position. ssize_t is an alias of the int type.


3. Remove Elements
The following is a summary of commonly used functions for removing elements from the _ Array container:
Void removeLastObject (). Remove the last element.
Void removeObject (Ref * object ). Removes an element.
Void removeObjectAtIndex (ssize_t index ). Removes an element from a specified position.
Void removeObjectsInArray (_ Array * otherArray ). Removes an Array _ Array object.
Void removeAllObjects (). Remove all elements.
Void fastRemoveObject (Ref * object ). Quickly remove an element.
Void fastRemoveObjectAtIndex (ssize_t index ). Quickly remove an element from a specified position.


4. Replacing and exchanging Elements
We can also use the following function to replace and exchange elements in the _ Array container:
Void exchangeObject (Ref * object1, Ref * object2 ). Exchange two elements.
Void exchangeObjectAtIndex (ssize_t index1, ssize_t index2 ). Swap two specified position elements.
Void replaceObjectAtIndex (ssize_t uIndex, Ref * object ). Replaces the specified position element with an object.


5. Other operation functions
In addition, there are many functions of the _ Array object. Below is a summary of common functions:
Ssize_t count (). Returns the number of elements.
Ssize_t capacity (). Returns the capacity of _ Array.
Ssize_t indexOfObject (Ref * object ). Returns the position of the specified Ref object pointer.
Ref * objectAtIndex (ssize_t index ). Returns the Ref object pointer at the specified position.
Ref * lastObject (). Returns the last element.
Ref * randomObject (). Returns a random element.
Bool containsObject (Ref * object ). Returns whether an element exists in the _ Array container.
Bool isEqualToArray (_ Array * pOtherArray ). Determine whether _ Array objects are equal.
Void reverseObjects (). Invert the _ Array container.


6. Traverse _ Array container
The Cocos2d-x provides two macros for traversing the _ Array container:
CCARRAY_FOREACH. Forward traversal.
CCARRAY_FOREACH_REVERSE. Reverse traversal.


Instance :__ Array container
Next we will introduce the related functions in the _ Array container through an example. Scenario: Click Go in the lower-right corner to add 100 genie to the scenario.

_ Array container instance

To implement the above functions, we do not use _ Array. However, to familiarize ourselves with the _ Array class, we specifically use the _ Array class in this example.
Let's take a look at the code section. The HelloWorldScene. h code is as follows:

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"#define MAX_COUNT 100①class HelloWorld : public cocos2d::Layer{cocos2d::__Array* list;②public:~HelloWorld();③    static cocos2d::Scene* createScene();    virtual bool init();          void menuCloseCallback(cocos2d::Ref* pSender);        CREATE_FUNC(HelloWorld);};#endif // __HELLOWORLD_SCENE_H__


Line 1 of the above Code # define MAX_COUNT 100 defines the macro MAX_COUNT, which defines the number of genie generated at a time. The list of member variables declared by the Code in line ② _ Array. The Code in line ③ declares the destructor. We need to release the member variable list in the destructor.
The init function code in HelloWorldScene. cpp is as follows:
bool HelloWorld::init(){if ( !Layer::init() ){return false;}Size visibleSize = Director::getInstance()->getVisibleSize();Vec2 origin = Director::getInstance()->getVisibleOrigin();auto goItem = MenuItemImage::create("go-down.png","go-up.png",CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));goItem->setPosition(Vec2(origin.x + visibleSize.width - goItem->getContentSize().width/2 ,origin.y + goItem->getContentSize().height/2));auto menu = Menu::create(goItem, NULL);menu->setPosition(Vec2::ZERO);this->addChild(menu, 1);this->list  = __Array::createWithCapacity(MAX_COUNT);①this->list->retain();②for(int i = 0;i < MAX_COUNT; ++i){Sprite* sprite = Sprite::create("Ball.png");③this->list->addObject(sprite);④}return true;}


Init is a function used to initialize the scenario. We created 100 genie in this function and put them in the list member variable of the _ Array * type. The Code in line ① is to create a list member variable of the _ Array * type and use the createWithCapacity function. The parameter is the initial capacity of the list container. Line ② code this-> list-> retain () is very important. The list container object created using the static function createWithCapacity is autorelease. If the retain () function is not called to keep the memory, when the init function ends, the list container object is automatically released, so that an error occurs when you use the list container object in other functions. The Code in line ③ is to create the genie object cyclically. The Code in line ④ adds the genie to the list container object. However, note that these genie objects have not been added to the scene, therefore, they do not appear when the scenario is displayed.
The menuCloseCallback function code in HelloWorldScene. cpp is as follows:
void HelloWorld::menuCloseCallback(Ref* pSender){log("list->count() = %d",this->list->count());Size visibleSize = Director::getInstance()->getVisibleSize();Ref* obj = nullptr;CCARRAY_FOREACH(this->list, obj) {①Sprite* sprite = (Sprite*)obj;②int x = CCRANDOM_0_1() * visibleSize.width;③int y = CCRANDOM_0_1() * visibleSize.height;④sprite->setPosition( Vec2(x, y) );this->removeChild(sprite);this->addChild(sprite);}}


This function is called after the player touches the Go button. The first line of code uses the CCARRAY_FOREACH macro to traverse the data in the list container cyclically. The Code in line ② is Sprite * sprite = (Sprite *) obj to get the Sprite object. The Code in line ③ CCRANDOM_0_1 () * visibleSize. width is the X axis coordinate randomly generated, and CCRANDOM_0_1 () is to generate 0 ~ Macro of the random number between 1. Similar to line 4, the Code randomly generates the Y axis coordinates of the genie.
The Destructor code in HelloWorldScene. cpp is as follows:
HelloWorld::~HelloWorld(){this->list->removeAllObjects();①CC_SAFE_RELEASE_NULL(this->list);②}


To release some resources in the destructor, line ① code this> list> removeAllObjects () is to remove all objects in the list container, but this does not release the list container object itself. Line ② code CC_SAFE_RELEASE_NULL (this-> list) is the list container object that safely releases the member variable list. CC_SAFE_RELEASE_NULL first releases the list container object and then assigns it to nullptr.


More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.cOcoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51wOrk6.com
Welcome to Cocos2d-x Technology Discussion Group: 257760386

Welcome to Zhijie iOS public classroom Platform



Why?

I think it's good!
 
Sprite drag in cocos2d-x

In touchmove, it should be okay to modify the sprite coordinate value spirte-> setposition (touchpoint ).

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.