Cocos2d-x 3.x basic learning: 3.2 detailed summary of node class Node

Cocos2d-x 3.x Compared with 2.x, the attributes and functions of the node class Node have been greatly modified and increased. Let’s take version 3.2 as an example today to summarize.

【Node】

The Node class is the parent class of most classes (not all classes, for example, the Director class directly inherits the Ref class), such as Scene, Layer, Sprite, and sprite collection SpriteBatchNode, etc. The parent class is Node.

The Node class contains some basic attributes, node-related, action execution, and timer related operations.

Of course, Node also has a parent class, whose parent class is Ref.

The inheritance relationship is as follows:

 

 

The main features of a node:

They can contain other node objects (addChild, getChildByTag, removeChild, etc);

They can schedule regular callbacks (schedule, unschedule, etc);

They can perform some actions (runAction, stopAction, etc);

The subclass node usually means (single/all):

* Rewrite initialization resources and can arrange callbacks;

* Create a callback to operate the time;

* Override "draw" to render nodes;

The attributes of the node are: position, zoom, rotation, tilt, anchor point, content size, visibility;

The following will introduce some of the commonly used operating functions of the node, as well as the new features.

(1) The attributes of the node

(2) Node operation

(3) Action related Action

(4) Timer related schedule

(5)Integrate NodeRBGA class

(6) Find the child node enumerateChildren

(7) Rendering order zOrder

(8) Coordinate conversion

1. The attributes of the node

The attributes of the node are: position, zoom, rotation, tilt, anchor point, content size, and visibility.

//

/**

* Position

* Set the coordinates of the node (x, y). The coordinates in OpenGL

* Add 3D coordinates

* Add standardized coordinate settings

*/

virtual void setPosition(const Vec2 &position); //Vec2坐标

virtual void setPosition(float x, float y); //(x,y), more efficient than Vec2

virtual void setPositionX(float x);

virtual void setPositionY(float y);

virtual const Vec2& getPosition() const;

virtual void getPosition(float* x, float* y) const;

virtual float getPositionX(void) const;

virtual float getPositionY(void) const;

//Increase 3D coordinates

virtual void setPosition3D(const Vec3& position); //Vec3坐标

virtual Vec3 getPosition3D() const;

virtual void setPositionZ(float positionZ);

virtual float getPositionZ() const;

//Add standardized coordinate settings

//Node's position pixel will be calculated according to the size of its parent node

//Size s = getParent()->getContentSize();

//_position = pos * s;

virtual void setNormalizedPosition(const Vec2 &position);

virtual const Vec2& getNormalizedPosition() const;

/**

* Scale

* Set the scale of the node. Scale the XYZ axis

* For example, a picture. Scale its width X, height Y, depth Z

*/

virtual void setScaleX(float scaleX); //Zoom out X

virtual void setScaleY(float scaleY); //Zoom height Y

virtual void setScaleZ(float scaleZ); //Zoom depth Z

virtual void setScale(float scaleX, float scaleY); //X scales fScaleX times, Y scales fScaleY times

virtual void setScale(float scale); //XYZ zooms in and out at the same time

virtual float getScaleX() const;

virtual float getScaleY() const;

virtual float getScaleZ() const;

virtual float getScale() const; //When the x and y scale factors are the same, get the scale factor of the node

/**

* Rotation

* Set the rotation angle of the node. Negative clockwise, positive counterclockwise rotation

* Add 3D rotation

*/

virtual void setRotation(float rotation);

virtual float getRotation() const;

//Increase 3D rotation

virtual void setRotation3D(const Vec3& rotation);

virtual Vec3 getRotation3D() const;

/**

* Tilt Skew

* Set the tilt angle of the XY axis

* setRotationalSkew() simulates the tilt function of Flash

* setSkew() uses the real tilt function

*/

virtual void setSkewX(float skewX); //Horizontal rotation and tilt. Negative clockwise deformation

virtual void setSkewY(float skewY); //Vertical rotation and tilt

virtual void setRotationSkewX(float rotationX);

virtual void setRotationSkewY(float rotationY);

virtual float getSkewX() const;

virtual float getSkewY() const;

virtual float getRotationSkewX() const;

virtual float getRotationSkewY() const;

/**

* AnchorPoint

* The anchor point is like a pushpin, pinning the picture on the screen. The anchor point is the coordinate of the picture.

* Of course, the pushpin can be pinned to the lower left corner, upper right corner, or the center of the picture.

* (0,0) means the lower left corner, (1,1) means the upper right corner

* The default anchor point is (0.5,0.5), which is the exact center of the node

*/

virtual void setAnchorPoint(const Vec2& anchorPoint); //Standardized anchor point

virtual const Vec2& getAnchorPoint() const; //Standardized anchor point

virtual const Vec2& getAnchorPointInPoints() const; //Returns the anchor point of absolute pixels, that is, screen coordinates

//Whether to ignore the anchor point setting

//If the anchor point setting is ignored, the anchor point will always be (0,0)

//The default value is false, but it is true in Layer and Scene

//This is an internal method, only used by Layer and Scene, don't call it yourself!

virtual void ignoreAnchorPointForPosition(bool ignore);

virtual bool isIgnoreAnchorPointForPosition() const;

/**

* Content Size

* contentSize is still the same regardless of whether the node is scaled or rotated

* All nodes have sizes, and layers and scenes have the same screen size

*/

virtual void setContentSize(const Size& contentSize);

virtual const Size& getContentSize() const;

/**

* Visible

*/

virtual void setVisible(bool visible);

virtual bool isVisible() const;

//

2. Node operation

Node operations include: tag, name, custom data, parent node management, child node management, and other operation management.

//

/**

* Tag and Name

* setTag: set a number to the node

* setName: set a name for the node

*/

virtual void setTag(int tag);

virtual void setName(const std::string& name);

virtual int getTag() const;

virtual std::string getName() const;

/**

* Custom data UserData/Object

* setUserData: Set a user-defined data. It can be a data block, structure or an object.

* setUserObject: Set a user-defined object. Similar to userData, but it is an object instead of void*

*/

virtual void setUserData(void *userData);

virtual void setUserObject(Ref *userObject);

virtual void* getUserData();

virtual Ref * getUserObject ();

/**

* Set the parent node Parent

* setParent , removeFromParent

*/

virtual void setParent(Node* parent);

virtual Node* getParent();

virtual void removeFromParent();

virtual void removeFromParentAndCleanup(bool cleanup); //true will delete all actions and callback functions of the node.

/**

* Manage child node Child

* addChild ,

* getChildBy** , getChildren , getChildrenCount

* removeChild , removeAllChildren

* reorderChild , sortAllChildren

*/

//Add child node

//localZOrder Z axis order is the priority of painting

//tag node number, child nodes can be obtained through tag

//name node name, child nodes can be obtained by name

virtual void addChild(Node * child);

virtual void addChild(Node * child, int localZOrder);

virtual void addChild(Node* child, int localZOrder, int tag);

virtual void addChild(Node* child, int localZOrder, const std::string &name);

//Get child nodes

virtual Node* getChildByTag(int tag) const;

virtual Node* getChildByName(const std::string& name) const;

virtual Vector& getChildren(); //Get all child nodes and return them as Vector array

virtual ssize_t getChildrenCount() const; //Total number of child nodes

//Delete child nodes

virtual void removeChild(Node* child, bool cleanup = true);

virtual void removeChildByTag(int tag, bool cleanup = true);

virtual void removeChildByName(const std::string &name, bool cleanup = true);

virtual void removeAllChildren(); //Delete all nodes

virtual void removeAllChildrenWithCleanup(bool cleanup); //cleanup is true to delete all actions of child nodes

//Rearrange child nodes

//Reorder a child node and set a new value of the z axis

//child it must have been added

//localZOrder Z axis order for drawing priority

virtual void reorderChild(Node * child, int localZOrder);

virtual void sortAllChildren(); //Reorder all child nodes

/**

* Other operation management

*/

virtual void onEnter(); //Called when the node starts to enter the stage. It is called when it is created.

virtual void onEnterTransitionDidFinish(); //Called after the node enters the stage. That is, it is called after creation.

virtual void onExit(); //Called when the node leaves the stage. Called when it is removed

virtual void onExitTransitionDidStart(); //Called before the node leaves the stage.

//Draw nodes

virtual void draw() final;

//Recursively visit all child nodes and redraw

virtual void visit() final;

//Return the Scene (scene) that contains the Node (node).

//If it does not belong to any scene, it will return nullptr

virtual Scene* getScene() const;

//Return the rectangular bounding box of the node in the coordinates of the parent node

virtual Rect getBoundingBox() const;

//Pause all active actions and schedulers

virtual void cleanup();

//

3. Action related Action

Action management: run, pause, cancel and other operations.

//

/**

* Action management Action

* setActionManager

* runAction, stopAction, getActionByTag, getNumberOfRunningActions

*/

//Set the ActionManager object used by all actions

//If you set a new ActionManager, the previously created action will be deleted

virtual void setActionManager(ActionManager* actionManager);

virtual ActionManager* getActionManager();

Action* runAction(Action* action); //Execute an action

Action* getActionByTag(int tag); //Get action, according to tag

void stopAllActions(); //Pause action

void stopAction(Action* action); //Pause action

void stopActionByTag(int tag); //Pause action

ssize_t getNumberOfRunningActions() const; //Get the number of running actions

//

4. Timer related schedule

Timer management, default timer, custom timer, one-time timer.

//

/**

* Timer management schedule

* setScheduler

* scheduleUpdate: default timer

* schedule: custom timer

* scheduleOnce: one-time timer

*/

//Set up a scheduler object to schedule all "update" and timers

//If you set a new scheduler, the timers/updates created before will be deleted.

virtual void setScheduler(Scheduler* scheduler);

virtual Scheduler* getScheduler(); //Get the scheduler object

//Turn on the default timer. The number of refreshes is 60 times/second. That is, 60 frames per second.

//Corresponding to the update (float delta) callback function.

//Give the timer priority priority. The smaller the priority, the higher the priority

void scheduleUpdate(void);

void scheduleUpdateWithPriority(int priority);

void unscheduleUpdate(void); //Cancel the default timer

virtual void update(float delta); //update is the callback function of the scheduleUpdate timer.

//Set a custom timer. The default is 60 frames per second.

//interval: Execute once every interval seconds.

//repeat: number of repetitions.

//delay: Delay time, that is, start execution after the timer delay is created.

void schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay);

void schedule(SEL_SCHEDULE selector, float interval);

void schedule(SEL_SCHEDULE selector); //The default is 60 frames per second

void scheduleOnce(SEL_SCHEDULE selector, float delay); //Execute only once, execute after delay seconds

void unschedule(SEL_SCHEDULE selector); //Cancel a custom timer

void unscheduleAllSelectors(void); //Cancel all timers

void resume(void); //Resume all timers and actions

void pause(void); //Pause all timers and actions

//

5. Integrate NodeRGBA class

Integrate NodeRGBA class, increase color and transparency settings.

//

/**

* Integrate NodeRGBA class

* setOpacity: transparency

* setColor: color

*/

virtual GLubyte getOpacity() const;

virtual GLubyte getDisplayedOpacity() const;

virtual void setOpacity (GLubyte opacity);

virtual const Color3B& getColor() const;

virtual const Color3B& getDisplayedColor() const;

virtual void setColor(const Color3B& color);

//

6、enumerateChildren

Added Node::enumerateChildren method, and supports C++11 regular expressions.

It is used to enumerate the child nodes of a Node node and let the child nodes whose names match the "name wildcard" execute the callback function.

And the return type of the callback function should be a bool value, and when it returns true, the search ends.

//

virtual void enumerateChildren(const std::string &name, std::function callback) const;

//

Examples of use:

//

//Find nodes whose name is 'nameToFind' and end with digits.

node->enumerateChildren("nameToFind[[:digit:]]+",

[](Node* node) -> bool { ... return false; // return true to stop at first match });

//Find nodes whose name is 'nameToFind' and end with digits recursively.

node->enumerateChildren("nameToFind[[:digit:]]+",

[](Node* node) -> bool { ... return false; // return true to stop at first match });

//

Examples of wildcard matching:

//

//Search syntax options

'//': Recursively visit all child nodes, and can only be placed at the beginning of the search string

'..': Search is moved to the parent node of node, which can only be placed at the end of a string

'/': Search for the child node moved to node, which can be placed in any position except the beginning of the search string

//Code example

enumerateChildren("//MyName", ...): Recursively visit all child nodes of Node. Find child nodes matching "MyName"

enumerateChildren("[[:alnum:]]+", ...): Find in the children of Node. All items

enumerateChildren("A[[:digit:]]", ...): Find in the children of Node. Child nodes named "A0","A1",...,"A9"

enumerateChildren("Abby/Normal", ...): Find in the grandchildren of Node. Its node is "Normal" and its parent node is "Abby"

enumerateChildren("//Abby/Normal", ...): Recursively visit all child nodes of Node. Its node is "Normal" and its parent node is "Abby"

//

Note: Programs built with gccV4.8 or lower will crash when running. Since OTHER_LDFLAGS cannot be used in Xcode6 beta3, we use fat library including 64-bit library files on iOS. But Xcode 5.0 or lower does not support this method.

and so:

* Android compilation requires NDK R9D or above

* Linux compilation requires GCC4.9 or above

* iOS compilation requires Xcode5.1 or above

7. Rendering order

In 2.x, Zorder is used to control the order of node rendering. The order of rendering in 3.x is determined by two factors.

Global Z order: GlobalZOrder. Comparison between all nodes.

Local Z order: LocalZOrder. Comparison between sibling nodes.

And the smaller the Z order, the first rendering.

7.1 Global Z order

Define the order of rendering nodes. The nodes with the smaller global Z order are rendered first.

Assumption: Two or more nodes have the same global Z order, then the rendering order cannot be guaranteed. The only exception is that if the global Z order of the node is zero, then the scene graph order can be used.

By default, the global Z order of all nodes is zero. This means that the scene graph order is used to render nodes by default.

The global Z order is very useful when you need to render nodes in a different order instead of the scene graph order.

Limitations: The global Z order cannot be used by nodes that have inherited "SpriteBatchNode".

//

virtual void setGlobalZOrder(float globalZOrder);

virtual float getGlobalZOrder() const;

//

7.2 Local Z order

LocalZOrder is the "key" to distinguish the correlation between a node and its sibling nodes.

The parent node will distinguish all child nodes by the value of LocalZOrder. If two nodes have the same LocalZOrder, the node that is added to the child node array first will be displayed in front of the node that is added later.

Similarly, the scene graph uses the "In-Order (in order)" traversal algorithm to traverse. And the node with the value of LocalZOrder less than 0 is the "left" subtree (left subtree), so the value node with the LocalZOrder greater than 0 is the "right" subtree (right subtree).

//

//Set the local Z order of this node ((relative to the sibling node))

virtual void setLocalZOrder(int localZOrder);

virtual int getLocalZOrder() const;

//

8. Coordinate conversion

Reference: "Cocos2d-x 3.0 Coordinate System Detailed Explanation"

8.1 Coordinate conversion function

There are two types of coordinates:

World coordinate: It is the world coordinate of the relative node.

Local coordinates: the coordinates of the relative node.

8.2 Example

 

 

 

 

The coordinates of node1 are: (20,40), and the anchor point (0,0).

The coordinates of node2 are: (-5,-20), anchor point (1,1).

Vec2 point1 = node1->convertToNodeSpace(node2->getPosition());

* The result is: (-25,-60). (Ie: relative node1 node coordinate position,, relative coordinate)

* Analysis: The coordinates of node2 relative to node1 are: (-5,-20)-(20,40).

* In other words: the coordinate position of node2 relative to node1.

Vec2 point2 = node1->convertToWorldSpace(node2->getPosition());

* The result is: (15,20). (Ie: relative to the world coordinate system of node1, the world coordinate)

* Analysis: Take node1 as a reference and convert to world coordinates: (20,40) + (-5,-20).

* In other words: the coordinates of node2 are now regarded as relative to the coordinate position of node1, and then converted to world coordinates.

8.3 Application in screen touch

Determine whether the touch point touches the inner area of ​​a sprite image sp.

//

bool HelloWorld::onTouchBegan(Touch *touch, Event *unused_event)

{

//Convert the contact coordinates to relative node sp, relative coordinates

Vec2 point = sp->convertTouchToNodeSpace(touch);

//Construct the size rectangle of sp

Size size = sp->getContentSize();

Rect rect = Rect(0, 0, size.width, size.height);

//Determine whether the contact touches the inside of sp

if (rect.containsPoint(point)) {

CCLog("Point in");

return true;

}

return false;

}

//

Guess you like

Origin blog.csdn.net/qq_21743659/article/details/108660045