首页 > 代码库 > CCNode Class-----Cocos2D-Swift v3.3
CCNode Class-----Cocos2D-Swift v3.3
CCNode Class Reference
Inherits from | CCResponder : NSObject |
Conforms to | CCSchedulerTarget |
Declared in | CCNode.h |
Overview
CCNode is the base class for all objects displayed by Cocos2D. CCNode handles transformations, can have a content size and provides a coordinate system for its child nodes.
CCNode是所有被Cocos2D显示的对象的基础类。CCNode处理转换,可以有内容的尺寸和提供为子nodes提供坐标系统.
Node Hierarchy
Nodes are hierachically organized in a tree with a CCScene as its root node. This is often referred to as scene graph, node hierarchy or node tree.
By default every node can have other nodes as child nodes. Some node classes restrict child nodes to a specific instance type, or don’t allow child nodes at all.
默认任何node都可以有子node,有些node类限制子node为特定类型或者根本不允许有子node。
A child node is positioned and rotated relative to its parent. Some properties of the parent node are “inherited” by child nodes, for example: scale,visible, paused. Other properties are only “inherited” if enabled, see cascadeOpacityEnabled for example.
子node的位置和旋转与父母node有关。
Draw Order
Draw order of nodes is controlled primarily by their order in the node hierarchy. The parent node is drawn first, followed by its child nodes in the order they were added.
You can fine-tune draw order via the zOrder property. By default all nodes have a zOrder of 0. Nodes with lower zOrder are drawn before nodes with higher zOrder. This applies only to nodes in the same level (sibling nodes) and their parent node, as the zOrder is relative to the zOrder of the parent.
Assuming you have two parent nodes A and B with zOrder 0 and they are drawn in the order A first, then B. Then all of the children of parent B will be drawn in front of any child node of parent A. If B’s zOrder is changed to -1, then parent B and all of its children will be drawn behind parent A and itschildren.
Scheduling Events / Timers
Implementing a method with a signature of -(void) update:(CCTime)delta
in a CCNode subclass will have that method run once every frame.CCTime
is declared as double
.
If this doesn’t suffice you can use the various schedule methods of a node, such as schedule:interval: or scheduleBlock:delay:. For example the following selector runs once every second:
[self schedule:@selector(everySecond:) interval:1.0];
The signature of scheduled selectors is always the same with a single CCTime parameter and no return value:
-(void) everySecond:(CCTime)delta { NSLog(@"tic-toc ..");}
Warning: Any non-Cocos2D scheduling methods will be unaffected by the node’s paused state and may run in indeterminate order, possibly causing rendering glitches and timing bugs. It is therfore strongly discouraged to use NSTimer, performSelector:afterDelay:
or Grand Central Disptach (GCD) dispatch_xxx
methods to time/schedule tasks in Cocos2D.
Pausing
It is common practice to pause the topmost node of a layer whose contents you want to pause. For instance you should have a gameLayer node that you can use to pause the entire game, while the hudLayer and pauseMenuLayer nodes may not need to or shouldn’t be paused in order to continue animations and allowing the user to interact with a pause menu.
Input Handling
Any CCNode or subclass can receive touch and mouse events, if enabled. See the CCResponder super class for more information.
Position and Size Types
Coordinates in the CCNode coordinate system are by default set in points by the position property. The point measurement provides a way to handle different screen pixel densities. For instance, on a Retina device one point corresponds to two pixels, but on non-Retina devices point and pixel resolution are identical.
By using the positionType property you can specify how a node’s position is interpreted. For instance, if you set the type to CCPositionTypeNormalized a position value of (0.5, 0.5) will place the node in the center of its parent’s container. The container is specified by the parent’s contentSize.
It’s also possible to set positions relative to the different corners of the parent’s container. The CCPositionType has three components, xUnit, yUnit and corner. The corner can be any reference corner of the parent’s container and the xUnit and yUnit can be any of the following:
- CCPositionUnitPoints - This is the default, the position value will be in points.
- CCPositionUnitScaled - The position is scaled by the UIScaleFactor as defined by CCDirector. This is very useful for scaling up game play without changing the game logic. E.g. if you want to support both phones and tablets in native resolutions.
- CCPositionUnitNormalized - Using the normalized type allows you to position object in relative to the parents container. E.g. it can be used to center nodes on the screen regardless of the device type your game is running on.
Similarily to how you set a node’s position and positionType you can also set it’s contentSize and contentSizeType. However, some classes doesn’t allow you to set these directly. For instance, the CCSprite sets its contentSize depending on the size of its texture and for descendants of CCControlyou should set the preferredSize and preferredSizeType rather than changing their contentSize directly. The CCSizeType has two components widthUnit and heightUnit which can be any of the following:
- CCSizeUnitPoints - This is the default, the size will be in points
- CCSizeUnitScaled - The size is scaled by the UIScaleFactor.
- CCSizeUnitNormalized - The content size will be set as a normalized value of the parent’s container.
- CCSizeUnitInset - The content size will be the size of it’s parent container, but inset by a number of points.
- CCSizeUnitInsetScaled - The content size will be the size of it’s parent container, but inset by a number of points multiplied by the UIScaleFactor.
Even if the positions and content sizes are not set in points you can use actions to animate the nodes. See the examples and tests for more information on how to set positions and content sizes, or use SpriteBuilder to easily play around with the settings. There are also more positioning options available by using CCLayout and CCLayoutBox.
Prefer to use ..InPoints
There are typically two properties of each property supporting a “type”. For instance the position property returns the raw values whose meaning depends on positionType, while positionInPoints will return the position in points regardless of positionType. It is recommended to use the “inPoints” variants of properties if you expect the values to be in points.
Otherwise your code will break if you subsequently change the positionType to something other than points (ie UIPoints or Normalized).
Subclassing Notes
A common pattern in building a Cocos2d game is to subclass CCNode, add it to a CCScene and override the methods for handling user input. Consider each node subclass as being the view in a MVC model, but it’s also the controller for this node and perhaps even the node’s branch of the node tree. The model can also be represented by the node subclass itself, or made separate (M-VC model).
A separate model could simply be any NSObject class initialized by the node subclass and assigned to an ivar/property.
An advanced subclassing style aims to minimize subclassing node classes except for CCNode itself. A CCNode subclass acts as the controller for itsnode tree, with one or more child nodes representing the controller node’s views. This is particularly useful for composite nodes, such as a player with multiple body parts (head, torso, limbs), attachments (armor, weapons) and effects (health bar, name label, selection rectangle, particle effects).
The userObject property can be used to add custom data and methods (model, components) to any node, in particular to avoid subclassing where the subclass would only add minimal functionality or just data.
Tasks
Creating a Node
+ node
Storing Custom Information
userObject
property
Position
position
propertypositionInPoints
propertypositionType
property
Rotation and Skew
rotation
propertyrotationalSkewX
propertyrotationalSkewY
propertyskewX
propertyskewY
property
Scale
scale
propertyscaleX
propertyscaleY
propertyscaleInPoints
propertyscaleXInPoints
propertyscaleYInPoints
propertyscaleType
property
Size
contentSize
propertycontentSizeInPoints
propertycontentSizeType
property– viewDidResizeTo:
– boundingBox
Content Anchor
anchorPoint
propertyanchorPointInPoints
property
Working with Node Trees
– addChild:
– addChild:z:
– addChild:z:name:
– removeFromParent
– removeChild:
– removeChildByName:
– removeAllChildren
parent
propertychildren
propertyscene
property
Removing Nodes without stopping Actions/Scheduling (unsafe!)
– removeFromParentAndCleanup:
– removeChild:cleanup:
– removeChildByName:cleanup:
– removeAllChildrenWithCleanup:
Naming Nodes
name
property– getChildByName:recursively:
Working with Actions
paused
propertyrunningInActiveScene
property– runAction:
– stopAllActions
– stopAction:
– stopActionByTag:
– getActionByTag:
– numberOfRunningActions
SpriteBuilder Animation Manager
animationManager
property
Scheduling Selectors and Blocks
– scheduleBlock:delay:
– schedule:interval:
– schedule:interval:repeat:delay:
– reschedule:interval:
– scheduleOnce:delay:
– unschedule:
– unscheduleAllSelectors
Transforms and Matrices
– nodeToParentTransform
– parentToNodeTransform
– nodeToWorldTransform
– worldToNodeTransform
Converting Point and Size "Types"
– convertPositionToPoints:type:
– convertPositionFromPoints:type:
– convertContentSizeToPoints:type:
– convertContentSizeFromPoints:type:
Converting to and from the Node‘s Coordinate System
– convertToNodeSpace:
– convertToWorldSpace:
– convertToNodeSpaceAR:
– convertToWorldSpaceAR:
– convertToWindowSpace:
Visibility and Draw Order
visible
propertyzOrder
property
Color
color
propertycolorRGBA
propertydisplayedColor
propertycascadeColorEnabled
property
Opacity (Alpha)
opacity
propertydisplayedOpacity
propertycascadeOpacityEnabled
property
Rendering (Implemented in Subclasses)
– draw:transform:
Scene Management (Implemented in Subclasses)
– onEnter
– onEnterTransitionDidFinish
– onExit
– onExitTransitionDidStart
Physics Body
physicsBody
property
CCPhysics Methods
– physicsNode
Debug Methods
– walkSceneGraph:
Properties
anchorPoint
The anchorPoint is the point around which all transformations (scale, rotate) and positioning manipulations take place. The anchorPoint is normalized, like a percentage. (0,0) refers to the bottom-left corner and (1,1) refers to the top-right corner. The default anchorPoint is (0,0). It starts in the bottom-left corner. CCSprite and some other node subclasses may have a different default anchorPoint, typically centered on the node (0.5,0.5).
@property (nonatomic, readwrite) CGPoint anchorPoint
Discussion
Warning: The anchorPoint is not a replacement for moving a node. It defines how the node’s content is drawn relative to the node’s position.
See Also
@property anchorPointInPoints
Declared In
CCNode.h
anchorPointInPoints
The anchorPoint in absolute points. It is calculated as follows: x =
contentSizeInPoints.width *
anchorPoint.x; y =
contentSizeInPoints.height *
anchorPoint.y;
@property (nonatomic, readonly) CGPoint anchorPointInPoints
Discussion
Note: The returned point is relative to the node’s contentSize origin, not relative to the node’s position.
See Also
@property anchorPoint
Declared In
CCNode.h
animationManager
Returns the Animation Manager of this node, or that of its parent.
@property (nonatomic, readonly) CCAnimationManager *animationManager
Discussion
Note: The animationManager property is nil during a node’s init methods.
See Also
CCAnimationManager
Declared In
CCNode.h
cascadeColorEnabled
CascadeColorEnabled causes changes to this node’s color to cascade down to it’s children. The new color is multiplied in with the color of each child, so it doesn’t bash the current color of those nodes. Opacity is unaffected by this property, see cascadeOpacityEnabled to change the alpha of nodes.
@property (nonatomic, getter=isCascadeColorEnabled) BOOL cascadeColorEnabled
See Also
@property color
@property colorRGBA
@property displayedColor
@property opacity
Declared In
CCNode.h
cascadeOpacityEnabled
CascadeOpacity causes changes to this node’s opacity to cascade down to it’s children. The new opacity is multiplied in with the opacity of each child, so it doesn’t bash the current opacity of those nodes. Color is unaffected by this property. See cascadeColorEnabled for color changes.
@property (nonatomic, getter=isCascadeOpacityEnabled) BOOL cascadeOpacityEnabled
See Also
@property opacity
@property displayedOpacity
Declared In
CCNode.h
children
Array of child nodes. Used to enumerate child nodes, for instance the following allows you to perform a task on all child nodes with a matching name:
@property (nonatomic, readonly) NSArray *children
Discussion
for (CCNode* child in self.children){ if ([child.name isEqualToString:@"so we meet again"]) { // do stuff here ... }}
Declared In
CCNode.h
color
Sets and returns the node’s color. Alpha is ignored. Changing color has no effect on nonvisible nodes (ie CCNode, CCScene).
@property (nonatomic, strong) CCColor *color
Discussion
Note: By default color is not “inherited” by child nodes. This can be enabled via cascadeColorEnabled.
See Also
CCColor
@property colorRGBA
@property opacity
@property cascadeColorEnabled
Declared In
CCNode.h
colorRGBA
Sets and returns the node’s color including alpha. Changing color has no effect on nonvisible nodes (ie CCNode, CCScene).
@property (nonatomic, strong) CCColor *colorRGBA
Discussion
Note: By default color is not “inherited” by child nodes. This can be enabled via cascadeColorEnabled.
See Also
CCColor
@property color
@property opacity
@property cascadeColorEnabled
Declared In
CCNode.h
contentSize
The untransformed size of the node in the unit specified by contentSizeType property. The contentSize remains the same regardless of whether thenode is scaled or rotated.
@property (nonatomic, readwrite, assign) CGSize contentSize
See Also
@property contentSizeInPoints
@property contentSizeType
Declared In
CCNode.h
contentSizeInPoints
The untransformed size of the node in Points. The contentSize remains the same regardless of whether the node is scaled or rotated. contentSizeInPoints will be scaled by the [CCDirector UIScaleFactor] if the contentSizeType is CCSizeUnitUIPoints.
@property (nonatomic, readwrite, assign) CGSize contentSizeInPoints
See Also
@property contentSize
@property contentSizeType
Declared In
CCNode.h
contentSizeType
Defines the contentSize type used for the width and height components of the contentSize property.
@property (nonatomic, readwrite, assign) CCSizeType contentSizeType
See Also
CCSizeType, CCSizeUnit
@property contentSize
@property contentSizeInPoints
Declared In
CCNode.h
displayedColor
Returns the actual color used by the node. This may be different from the color and colorRGBA properties if the parent node has cascadeColorEnabled.
@property (nonatomic, readonly) CCColor *displayedColor
See Also
CCColor
@property color
@property colorRGBA
Declared In
CCNode.h
displayedOpacity
Returns the actual opacity, in the range 0.0 to 1.0. This may be different from the opacity property if the parent node has cascadeOpacityEnabled.
@property (nonatomic, readonly) CGFloat displayedOpacity
See Also
@property opacity
Declared In
CCNode.h
name
A name tag used to help identify the node easily. Can be used both to encode custom data but primarily meant to obtain a node by its name.
@property (nonatomic, strong) NSString *name
See Also
- getChildByName:recursively:
@property userObject
Declared In
CCNode.h
opacity
Sets and returns the opacity in the range 0.0 (fully transparent) to 1.0 (fully opaque).
@property (nonatomic) CGFloat opacity
Discussion
Note: By default opacity is not “inherited” by child nodes. This can be enabled via cascadeOpacityEnabled.
Warning: If the the texture has premultiplied alpha then the RGB channels will be modified.
Declared In
CCNode.h
parent
A weak reference to the parent.
@property (nonatomic, readwrite, weak) CCNode *parent
Discussion
Warning: Never ever change the parent manually! This must be done exclusively by Cocos2D. This property is not readonly due to historical reasons, and this is prone to change.
Declared In
CCNode.h
paused
If paused is set to YES, all of the node’s actions and its scheduled selectors/blocks will be paused until the node is unpaused.
@property (nonatomic, assign) BOOL paused
Discussion
Changing the paused state of a node will also change the paused state of its children recursively.
Warning: Any non-Cocos2D scheduling methods will be unaffected by the paused state. It is strongly discouraged to use NSTimer,performSelector:afterDelay:
or Grand Central Disptach (GCD) dispatch_xxx
methods to time/schedule tasks in Cocos2D.
Declared In
CCNode.h
physicsBody
The physics body (if any) that this node is attached to. Initialize and assign a CCPhysicsBody instance to this property to have the node participate in the physics simulation.
@property (nonatomic, strong) CCPhysicsBody *physicsBody
See Also
CCPhysicsBody
- physicsNode
Declared In
CCNode.h
position
Position (x,y) of the node in the units specified by the positionType property. The distance is measured from one of the corners of the node’s parentcontainer, which corner is specified by the positionType property. Default setting is referencing the bottom left corner in points.
@property (nonatomic, readwrite, assign) CGPoint position
See Also
@property positionInPoints
@property positionType
Declared In
CCNode.h
positionInPoints
Position (x,y) of the node in points from the bottom left corner.
@property (nonatomic, readwrite, assign) CGPoint positionInPoints
See Also
@property position
Declared In
CCNode.h
positionType
Defines the position type used for the position property. Changing the position type affects the meaning of the values assigned to the position property and allows you to change the referenceCorner relative to the parent container. It also allows position to be interpreted as “UIPoints”, which are scaled by[CCDirector UIScaleFactor]. See “Coordinate System and Positioning” in Class Overview for more information.
@property (nonatomic, readwrite, assign) CCPositionType positionType
See Also
CCPositionType, CCPositionUnit, CCPositionReferenceCorner
@property position
@property positionInPoints
Declared In
CCNode.h
rotation
The rotation (angle) of the node in degrees. Rotation is relative to the parent node’s rotation. 0 is the default rotation angle. Positive values rotate nodeclockwise.
@property (nonatomic, readwrite, assign) float rotation
Declared In
CCNode.h
rotationalSkewX
The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node clockwise. It only modifies the X rotationperforming a horizontal rotational skew.
@property (nonatomic, readwrite, assign) float rotationalSkewX
See Also
@property skewX, @property skewY
Declared In
CCNode.h
rotationalSkewY
The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node clockwise. It only modifies the Y rotationperforming a vertical rotational skew.
@property (nonatomic, readwrite, assign) float rotationalSkewY
Declared In
CCNode.h
runningInActiveScene
Returns YES if the node is added to an active scene and neither it nor any of it’s ancestors is paused.
@property (nonatomic, readonly, getter=isRunningInActiveScene) BOOL runningInActiveScene
Declared In
CCNode.h
scale
The scale factor of the node. 1.0 is the default scale factor (original size). Meaning depends on scaleType. It modifies the X and Y scale at the same time, preserving the node’s aspect ratio.
@property (nonatomic, readwrite, assign) float scale
Discussion
Scale is affected by the parent node’s scale, ie if parent’s scale is 0.5 then setting the child’s scale to 2.0 will make the child node appear at its original size.
See Also
@property scaleInPoints
@property scaleType
@property scaleX, @property scaleY
Declared In
CCNode.h
scaleInPoints
The scaleInPoints is the scale factor of the node in both X and Y, measured in points. The scaleType property indicates if the scaleInPoints will be scaled by the UIScaleFactor or not. See “Coordinate System and Positioning” in class overview for more information.
@property (nonatomic, readonly) float scaleInPoints
Discussion
Scale is affected by the parent node’s scale, ie if parent’s scale is 0.5 then setting the child’s scale to 2.0 will make the child node appear at its original size.
See Also
@property scale
@property scaleType
Declared In
CCNode.h
scaleType
The scaleType defines scale behavior for this node. CCScaleTypeScaled indicates that the node will be scaled by [CCDirector UIScaleFactor]. This property is analagous to positionType. ScaleType affects the scaleInPoints of a CCNode. See “Coordinate System and Positioning” in class overview for more information.
@property (nonatomic, assign) CCScaleType scaleType
See Also
CCScaleType
@property scale
@property scaleInPoints
Declared In
CCNode.h
scaleX
The scale factor of the node. 1.0 is the default scale factor. It only modifies the X scale factor.
@property (nonatomic, readwrite, assign) float scaleX
Discussion
Scale is affected by the parent node’s scale, ie if parent’s scale is 0.5 then setting the child’s scale to 2.0 will make the child node appear at its original size.
See Also
@property scaleY
@property scaleXInPoints
@property scale
Declared In
CCNode.h
scaleXInPoints
The scaleInPoints is the scale factor of the node in X, measured in points.
@property (nonatomic, readonly) float scaleXInPoints
Discussion
Scale is affected by the parent node’s scale, ie if parent’s scale is 0.5 then setting the child’s scale to 2.0 will make the child node appear at its original size.
See Also
@property scaleY, @property scaleYInPoints
Declared In
CCNode.h
scaleY
The scale factor of the node. 1.0 is the default scale factor. It only modifies the Y scale factor.
@property (nonatomic, readwrite, assign) float scaleY
Discussion
Scale is affected by the parent node’s scale, ie if parent’s scale is 0.5 then setting the child’s scale to 2.0 will make the child node appear at its original size.
See Also
@property scaleX
@property scaleYInPoints
@property scale
Declared In
CCNode.h
scaleYInPoints
The scaleInPoints is the scale factor of the node in Y, measured in points.
@property (nonatomic, readonly) float scaleYInPoints
Discussion
Scale is affected by the parent node’s scale, ie if parent’s scale is 0.5 then setting the child’s scale to 2.0 will make the child node appear at its original size.
See Also
@property scaleX
@property scaleXInPoints
Declared In
CCNode.h
scene
The scene this node is added to, or nil if it’s not part of a scene.
@property (nonatomic, readonly) CCScene *scene
Discussion
Note: The scene property is nil during a node’s init methods. The scene property is set only after addChild: was used to add it as a child node to anode that already is in the scene.
See Also
CCScene
Declared In
CCNode.h
skewX
The X skew angle of the node in degrees. This angle describes the shear distortion in the X direction. Thus, it is the angle between the Y axis and the left edge of the shape The default skewX angle is 0, with valid ranges from -90 to 90. Positive values distort the node in a clockwise direction.
@property (nonatomic, readwrite, assign) float skewX
See Also
@property skewY, @property rotationalSkewX
Declared In
CCNode.h
skewY
The Y skew angle of the node in degrees. This angle describes the shear distortion in the Y direction. Thus, it is the angle between the X axis and the bottom edge of the shape The default skewY angle is 0, with valid ranges from -90 to 90. Positive values distort the node in a counter-clockwise direction.
@property (nonatomic, readwrite, assign) float skewY
See Also
@property skewX, @property rotationalSkewY
Declared In
CCNode.h
userObject
Used to store a custom object of any type. For instance you could add a NSMutableDictionary to store custom data in a node without needing to subclass the node.
@property (nonatomic, readwrite, strong) id userObject
Declared In
CCNode.h
visible
Whether the node and its children are visible. Default is YES.
@property (nonatomic, readwrite, assign) BOOL visible
Discussion
Note: The children nodes will not change their visible property. Nevertheless they won’t be drawn if their parent’s visible property is NO. This means even if a node’s visible property may be YES it could still be invisible if one of its parents has visible set to NO.
Note: Nodes that are not visible will not be rendered. For recurring use of the same nodes it is typically more efficient to temporarily setnode
.visible = NO
compared to removeFromParent and a subsequent addChild:.
Declared In
CCNode.h
zOrder
The draw order of the node relative to its sibling (having the same parent) nodes. The default is 0.
@property (nonatomic, assign) NSInteger zOrder
Discussion
A zOrder of less than 0 will draw nodes behind their parent, a zOrder of 0 or greater will make the nodes draw in front of their parent.
A parent nodes with a lower zOrder value will have itself and its children drawn behind another parent node with a higher zOrder value. The zOrder property only affects sibling nodes and their parent, it can not be used to change the draw order of nodes with different parents - in that case adjust the parent node’s zOrder.
Note: Any sibling nodes with the same zOrder will be drawn in the order they were added as children. It is slightly more efficient (and certainly less confusing) to make this natural order work to your advantage.
Declared In
CCNode.h
Class Methods
node
Creates and returns a new node.
+ (id)node
Discussion
Note: Not all subclasses support initialization via the node
initializer. Prefer to use specialized initializers in CCNode subclasses, where available.
Declared In
CCNode.h
Instance Methods
addChild:
Adds a child to the container with default zOrder (0). If the child is added to a ‘running’ node, then ‘onEnter’ and ‘onEnterTransitionDidFinish’ will be sent to the node immediately.
- (void)addChild:(CCNode *)node
Parameters
- node
CCNode to add as a child.
See Also
- addChild:z:
- addChild:z:name:
Declared In
CCNode.h
addChild:z:
Adds a child to the container with the given zOrder. If the child is added to a ‘running’ node, then ‘onEnter’ and ‘onEnterTransitionDidFinish’ will be sent to the node immediately.
- (void)addChild:(CCNode *)node z:(NSInteger)z
Parameters
- node
CCNode to add as a child.
- z
Draw order of node. This value will be assigned to the node’s zOrder property.
See Also
- addChild:, - addChild:z:name:
@property zOrder
Declared In
CCNode.h
addChild:z:name:
Adds a child to the container with z order and tag. If the child is added to a ‘running’ node, then ‘onEnter’ and ‘onEnterTransitionDidFinish’ will be called immediately.
- (void)addChild:(CCNode *)node z:(NSInteger)z name:(NSString *)name
Parameters
- node
CCNode to add as a child.
- z
Draw order of node. This value will be assigned to the node’s zOrder property.
- name
Name for this node. This string will be assigned to the node’s name property.
See Also
- addChild:, - addChild:z:
@property zOrder
@property name
Declared In
CCNode.h
boundingBox
Returns an axis aligned bounding box in points, in the parent node’s coordinate system.
- (CGRect)boundingBox
See Also
@property contentSize
- nodeToParentTransform
Declared In
CCNode.h
convertContentSizeFromPoints:type:
Converts the given size in points to size values converted based on the provided CCSizeType.
- (CGSize)convertContentSizeFromPoints:(CGSize)pointSize type:(CCSizeType)type
Parameters
- pointSize
The size in points to convert.
- type
How the input size values should be converted.
Return Value
The size values in the format specified by type.
See Also
@property contentSize
CCSizeType, CCSizeUnit
Declared In
CCNode.h
convertContentSizeToPoints:type:
Converts the given content size values to a size in points.
- (CGSize)convertContentSizeToPoints:(CGSize)contentSize type:(CCSizeType)type
Parameters
- contentSize
The contentSize values to convert.
- type
How the input contentSize values should be interpreted.
Return Value
The converted size in points.
See Also
@property contentSizeInPoints
CCSizeType, CCSizeUnit
Declared In
CCNode.h
convertPositionFromPoints:type:
Converts the given position in points to position values converted based on the provided CCPositionType.
- (CGPoint)convertPositionFromPoints:(CGPoint)positionInPoints type:(CCPositionType)type
Parameters
- positionInPoints
The position in points to convert.
- type
How the input position values should be converted.
Return Value
The position values in the format specified by type.
See Also
@property position
CCPositionType, CCPositionUnit, CCPositionReferenceCorner
Declared In
CCNode.h
convertPositionToPoints:type:
Converts the given position values to a position in points.
- (CGPoint)convertPositionToPoints:(CGPoint)position type:(CCPositionType)type
Parameters
- position
The position values to convert.
- type
How the input position values should be interpreted.
Return Value
The converted position in points.
See Also
@property positionInPoints
CCPositionType, CCPositionUnit, CCPositionReferenceCorner
Declared In
CCNode.h
convertToNodeSpace:
Converts a Point to node (local) space coordinates. The result is in Points.
- (CGPoint)convertToNodeSpace:(CGPoint)worldPoint
Parameters
- worldPoint
World position in points.
Return Value
Local position in points.
Declared In
CCNode.h
convertToNodeSpaceAR:
Converts a Point to node (local) space coordinates. The result is in Points. Treats the returned/received node point as relative to the anchorPoint.
- (CGPoint)convertToNodeSpaceAR:(CGPoint)worldPoint
Parameters
- worldPoint
World position in points.
Return Value
Local position in points.
Declared In
CCNode.h
convertToWindowSpace:
Converts a local Point to Window space (UIKit) coordinates. The result is in Points.
- (CGPoint)convertToWindowSpace:(CGPoint)nodePoint
Parameters
- nodePoint
Local position in points.
Return Value
UI position in points.
Declared In
CCNode.h
convertToWorldSpace:
Converts a Point to world space coordinates. The result is in Points.
- (CGPoint)convertToWorldSpace:(CGPoint)nodePoint
Parameters
- nodePoint
Local position in points.
Return Value
World position in points.
Declared In
CCNode.h
convertToWorldSpaceAR:
Converts a local Point to world space coordinates. The result is in Points. Treats the returned/received node point as relative to the anchorPoint.
- (CGPoint)convertToWorldSpaceAR:(CGPoint)nodePoint
Parameters
- nodePoint
Local position in points.
Return Value
World position in points.
Declared In
CCNode.h
draw:transform:
Override this method to add custom rendering code to your node.
- (void)draw:(CCRenderer *)renderer transform:(const GLKMatrix4 *)transform
Parameters
- renderer
The CCRenderer instance to use for drawing.
- transform
The parent node’s transform.
Discussion
Note: You should only use Cocos2D’s CCRenderer API to modify the render state and shaders. For further info, please see the CCRendererdocumentation.
Warning: You must not call [super draw:transform:];
See Also
CCRenderer
Declared In
CCNode.h
getActionByTag:
Gets an action running on the node given its tag. If there are multiple actions with the same tag it will get the first action found that has this tag.
- (CCAction *)getActionByTag:(NSInteger)tag
Parameters
- tag
Tag of an action.
Return Value
The first action with the given tag, or nil if there’s no running action with this tag.
See Also
CCAction
Declared In
CCNode.h
getChildByName:recursively:
Search through the children of the container for one matching the name tag. If recursive, it returns the first matching node, via a depth first search. Otherwise, only immediate children are checked.
- (CCNode *)getChildByName:(NSString *)name recursively:(bool)isRecursive
Parameters
- name
The name of the node to look for.
- isRecursive
Search recursively through node’s children (its node tree).
Return Value
Returns the first node with a matching name, or nil if no node with that name was found.
Discussion
Note: Avoid calling this often, ie multiple times per frame, as the lookup cost can add up. Specifically if the search is recursive.
See Also
@property name
Declared In
CCNode.h
nodeToParentTransform
Returns the matrix that transform the node’s (local) space coordinates into the parent’s space coordinates. The matrix is in Pixels.
- (CGAffineTransform)nodeToParentTransform
See Also
CGAffineTransform
- parentToNodeTransform
Declared In
CCNode.h
nodeToWorldTransform
Returns the world affine transform matrix. The matrix is in Pixels.
- (CGAffineTransform)nodeToWorldTransform
See Also
CGAffineTransform
- nodeToParentTransform
- worldToNodeTransform
Declared In
CCNode.h
numberOfRunningActions
Returns the numbers of actions that are running plus the ones that are scheduled to run (actions in the internal actionsToAdd array).
- (NSUInteger)numberOfRunningActions
Discussion
Note: Composable actions are counted as 1 action. Example: - If you are running 2 Sequences each with 7 actions, it will return 2. - If you are running 7 Sequences each with 2 actions, it will return 7.
Declared In
CCNode.h
onEnter
Called every time the CCNode (or one of its parents) has been added to the scene, or when the scene is presented. If a new scene is presented with a transition, this event is sent to nodes when the transition animation starts.
- (void)onEnter
Discussion
Warning: You must call [super onEnter]
in your own implementation.
See Also
- onExit
- onEnterTransitionDidFinish
Declared In
CCNode.h
onEnterTransitionDidFinish
Called every time the CCNode (or one of its parents) has been added to the scene, or when the scene is presented. If a new scene is presented with a transition, this event is sent to nodes after the transition animation ended. Otherwise it will be called immediately after onEnter.
- (void)onEnterTransitionDidFinish
Discussion
Warning: You must call [super onEnterTransitionDidFinish]
in your own implementation.
See Also
- onEnter
- onExit
Declared In
CCNode.h
onExit
Called every time the CCNode is removed from the node tree. If a new scene is presented with a transition, this event is sent when the transition animation ended.
- (void)onExit
Discussion
Warning: You must call [super onExit]
in your own implementation.
See Also
- onEnter
- onExitTransitionDidStart
Declared In
CCNode.h
onExitTransitionDidStart
Called every time the CCNode is removed from the node tree. If a new scene is presented with a transition, this event is sent when the transition animation starts.
- (void)onExitTransitionDidStart
Discussion
Warning: You must call [super onExitTransitionDidStart]
in your own implementation.
See Also
- onExit
- onEnter
Declared In
CCNode.h
parentToNodeTransform
Returns the matrix that transform parent’s space coordinates to the node’s (local) space coordinates. The matrix is in Pixels.
- (CGAffineTransform)parentToNodeTransform
See Also
CGAffineTransform
- nodeToParentTransform
Declared In
CCNode.h
physicsNode
Nearest CCPhysicsNode ancestor of this node, or nil if none. Unlike [CCPhysicsBody physicsNode], this will return a value before onEnter is called on thenode.
- (CCPhysicsNode *)physicsNode
See Also
CCPhysicsNode
@property physicsBody
Declared In
CCPhysicsNode.h
removeAllChildren
Removes all children from the container.
- (void)removeAllChildren
Discussion
Note: It is unnecessary to call this when replacing scenes or removing nodes. All nodes call this method on themselves automatically when removed from a parent node or when a new scene is presented.
Declared In
CCNode.h
removeAllChildrenWithCleanup:
Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
- (void)removeAllChildrenWithCleanup:(BOOL)cleanup
Parameters
- cleanup
If YES, stops all scheduled events and actions of removed node.
Discussion
Note: Running [self removeAllChildrenWithCleanup:YES]
is identical to running [self removeAllChildren]
. You only need to use this method if you intend to not stop scheduler and actions, ie cleanup:NO
.
Warning: Setting cleanup to NO may prevent the children from deallocating. You have to ensure that the children are either re-added to the nodehierarchy at some point, or send them the cleanup
method when you no longer need the children (for instance before switching scenes).
See Also
- removeAllChildren
Declared In
CCNode.h
removeChild:
Removes a child from the container. The node must be a child of this node. Will stop the node’s scheduled selectors/blocks and actions.
- (void)removeChild:(CCNode *)child
Parameters
- child
The child node to remove.
Discussion
Note: It is recommended to use [node removeFromParent]
over [self removeChild:node]
as the former will always work, even in cases where (in this example) the node hierarchy has changed so that node no longer is a child of self.
Note: It is typically more efficient to change a node’s visible status rather than remove + addChild: if all you need is to temporarily remove the nodefrom the screen.
See Also
- removeFromParent
Declared In
CCNode.h
removeChild:cleanup:
Removes a child from the container. The node must be a child of this node. If cleanup is YES the node will also remove all of its actions and scheduled selectors/blocks.
- (void)removeChild:(CCNode *)node cleanup:(BOOL)cleanup
Parameters
- node
The child node to remove.
- cleanup
If YES, stops all scheduled events and actions.
Discussion
Note: Running [self removeChild:
node cleanup:YES]
is identical to running [self removeChild:node]
. You only need to use this method if you intend to not stop scheduler and actions, ie cleanup:NO
.
Note: It is recommended to use [node removeFromParent]
over [self removeChild:node]
as the former will always work, even in cases where (in this example) the node hierarchy has changed so that node no longer is a child of self.
Warning: Setting cleanup to NO may prevent the node and its children from deallocating. You have to ensure that the node is either re-added to thenode hierarchy at some point, or send it the cleanup
method when you no longer need the node (for instance before switching scenes).
See Also
- removeFromParent
- removeChild:
Declared In
CCNode.h
removeChildByName:
Removes a child from the container by name. Does nothing if there’s no node with that name. Will stop the node’s scheduled selectors/blocks and actions.
- (void)removeChildByName:(NSString *)name
Parameters
- name
Name of node to be removed.
Declared In
CCNode.h
removeChildByName:cleanup:
Removes a child from the container by name value. If cleanup is YES the node will also remove all of its actions and scheduled selectors/blocks.
- (void)removeChildByName:(NSString *)name cleanup:(BOOL)cleanup
Parameters
- name
Name of node to be removed.
- cleanup
Stops all scheduled events and actions.
Discussion
Note: Running [self removeChildByName:@"name" cleanup:YES]
is identical to running [self removeChildByName:@"name"]
. You only need to use this method if you intend to not stop scheduler and actions, ie cleanup:NO
.
Warning: Setting cleanup to NO may prevent the node and its children from deallocating. You have to ensure that the node is either re-added to thenode hierarchy at some point, or send it the cleanup
method when you no longer need the node (for instance before switching scenes).
See Also
- removeChildByName:
Declared In
CCNode.h
removeFromParent
Removes the node from its parent node. Will stop the node’s scheduled selectors/blocks and actions.
- (void)removeFromParent
Discussion
Note: It is typically more efficient to change a node’s visible status rather than remove + addChild: if all you need is to temporarily remove the nodefrom the screen.
See Also
@property visible
Declared In
CCNode.h
removeFromParentAndCleanup:
Removes the node from its parent node. If cleanup is YES the node will also remove all of its actions and scheduled selectors/blocks.
- (void)removeFromParentAndCleanup:(BOOL)cleanup
Parameters
- cleanup
Stops all scheduled selectors/blocks and actions. Set to NO if you intend to “continue” the node at a later point or simply want to reparent the node.
Discussion
Note: Running [self removeFromParentAndCleanup:YES]
is identical to running [self removeFromParent]
. You only need to use this method if you intend to not stop scheduler and actions, ie cleanup:NO
.
Warning: Setting cleanup to NO may prevent the node and its children from deallocating. You have to ensure that the node is either re-added to thenode hierarchy at some point, or send it the cleanup
method when you no longer need the node (for instance before switching scenes).
See Also
- removeFromParent
Declared In
CCNode.h
reschedule:interval:
Re-schedules a custom selector with an interval time in seconds. If the custom selector you pass in is not already scheduled, this method is equivalent to schedule:interval:.
The difference between this method and schedule:interval: is that if the selector is already scheduled, calling this method will only adjust the interval of the already scheduled selector.
- (CCTimer *)reschedule:(SEL)selector interval:(CCTime)interval
Parameters
- selector
Selector to run. The selector must have the following signature:
-(void) theSelector:(CCTime)delta
where theSelector is any legal selectorname. The parameter must be specified with the @selector keyword as@selector(theSelector:)
.
- interval
Interval between execution in seconds.
Discussion
In contrast, when you call schedule:interval: on an already scheduled selector, your custom selector will be unscheduled and then rescheduled which is less efficient.
See Also
CCTimer
Declared In
CCNode.h
runAction:
Has the node run an action.
- (CCAction *)runAction:(CCAction *)action
Parameters
- action
Action to run.
Return Value
The action that is executed (same as the one that was passed in).
Discussion
Note: Depending on when in the frame update cycle this method gets called, the action passed in may either start running in the current frame or in the next frame.
See Also
CCAction
Declared In
CCNode.h
schedule:interval:
Schedules a custom selector to run repeatedly at the given interval (in seconds). If the selector is already scheduled, then the interval parameter will be updated without scheduling it again.
- (CCTimer *)schedule:(SEL)selector interval:(CCTime)seconds
Parameters
- selector
Selector to run. The selector must have the following signature:
-(void) theSelector:(CCTime)delta
where theSelector is any legal selectorname. The parameter must be specified with the @selector keyword as@selector(theSelector:)
.
- seconds
Interval between executions in seconds.
Return Value
A newly initialized CCTimer object.
Discussion
Note: If interval is 0 the selector will run once every frame. It is recommended and slightly more efficient to implement the update: method instead. If the update: method is already implemented, just call a selector from update: that runs whatever selector you wanted to schedule with interval 0.
See Also
CCTimer
Declared In
CCNode.h
schedule:interval:repeat:delay:
Schedules a custom selector to run repeatedly at the given interval (in seconds).
- (CCTimer *)schedule:(SEL)selector interval:(CCTime)interval repeat:(NSUInteger)repeat delay:(CCTime)delay
Parameters
- selector
Selector to run. The selector must have the following signature:
-(void) theSelector:(CCTime)delta
where theSelector is any legal selectorname. The parameter must be specified with the @selector keyword as@selector(theSelector:)
.
- interval
Interval between executions in seconds.
- repeat
Number of times to repeat the selector. The selector will run repeat times plus one because the first run is not considered a “repeat”.
- delay
Delay before running the selector for the first time, in seconds.
Return Value
A newly initialized CCTimer object.
See Also
CCTimer
Declared In
CCNode.h
scheduleBlock:delay:
Schedules a block to run once, after the given delay.
- (CCTimer *)scheduleBlock:(CCTimerBlock)block delay:(CCTime)delay
Parameters
- block
Block to execute. The block takes a
CCTimer*
parameter as input and returns nothing.
- delay
Delay, in seconds.
Return Value
A newly initialized CCTimer object.
Discussion
CCTimerBlock
is a block typedef declared as void (^)(
CCTimer *timer)
Note: There is currently no way to stop/cancel an already scheduled block. If a scheduled block should not run under certain circumstances, the block’s code itself must check these conditions to determine whether it should or shouldn’t perform its task.
See Also
CCTimer
Declared In
CCNode.h
scheduleOnce:delay:
Schedules a selector that runs only once, with an initial delay.
- (CCTimer *)scheduleOnce:(SEL)selector delay:(CCTime)delay
Parameters
- selector
Selector to run. The selector must have the following signature:
-(void) theSelector:(CCTime)delta
where theSelector is any legal selectorname. The parameter must be specified with the @selector keyword as@selector(theSelector:)
.
- delay
Delay before selector runs, in seconds.
Return Value
A newly initialized CCTimer object.
See Also
CCTimer
Declared In
CCNode.h
stopAction:
Removes an action from the running action list.
- (void)stopAction:(CCAction *)action
Parameters
- action
Action to remove.
See Also
CCAction
Declared In
CCNode.h
stopActionByTag:
Removes an action from the running action list given its tag. If there are multiple actions with the same tag it will only remove the first action found that has this tag.
- (void)stopActionByTag:(NSInteger)tag
Parameters
- tag
Tag of action to remove.
Declared In
CCNode.h
stopAllActions
Stops and removes all actions running on the node. @node It is not necessary to call this when removing a node. Removing a node from its parent will also stop its actions.
- (void)stopAllActions
Declared In
CCNode.h
unschedule:
Unschedule an already scheduled selector. Does nothing if the given selector isn’t scheduled.
- (void)unschedule:(SEL)selector
Parameters
- selector
Selector to unschedule. The parameter must be specified with the @selector keyword as
@selector(theSelector:)
.
Declared In
CCNode.h
unscheduleAllSelectors
Unschedules all scheduled selectors.
- (void)unscheduleAllSelectors
Discussion
Note: When removing a node from its parent it will automatically unschedule all of its selectors. It is not required to explicitly call this method.
Declared In
CCNode.h
viewDidResizeTo:
Invoked automatically when the OS view has been resized.
- (void)viewDidResizeTo:(CGSize)newViewSize
Parameters
- newViewSize
The new size of the view after it has been resized.
Discussion
This implementation simply propagates the same method to the children. Subclasses may override to actually do something when the view resizes.
Declared In
CCNode.h
walkSceneGraph:
Prints on the debug console the scene graph
- (void)walkSceneGraph:(NSUInteger)level
Parameters
- level
Level of debug information.
Declared In
CCNode+Debug.h
worldToNodeTransform
Returns the inverse world affine transform matrix. The matrix is in Pixels.
- (CGAffineTransform)worldToNodeTransform
See Also
CGAffineTransform
- nodeToWorldTransform
Declared In
CCNode.h
CCNode Class-----Cocos2D-Swift v3.3