CCNode Class Reference

Inherits from CCResponder : NSObject
Conforms to CCBlendProtocol
CCSchedulerTarget
CCShaderProtocol
CCTextureProtocol
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.

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.

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.

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 its children.

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 CCControl you 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 CocosBuilder 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 its node 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.

Cleanup of nodes

When a node is no longer needed, and is removed (directly or indirectly) from it’s parent by one of:

-(void) removeFromParentAndCleanup:(BOOL)cleanup; -(void) removeChild: (CCNode)node cleanup:(BOOL)cleanup; -(void) removeChildByName:(NSString)name cleanup:(BOOL)cleanup; -(void) removeAllChildrenWithCleanup:(BOOL)cleanup;

and the cleanup parameter is YES, the private method:

  • (void) cleanup;

is called. This offers an opportunity for the node to carry out any cleanup such as removing possible circular references that might cause a memory leak.

Note: that if you override cleanup, you must call [super cleanup] after any cleanup of your own.

Creating a Node

+ node

Creates and returns a new node.

+ (instancetype)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

Storing Custom Information

  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

Position

  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 parent container, which corner is specified by the positionType property. Default setting is referencing the bottom left corner in points.

@property (nonatomic, readwrite, assign) CGPoint position

Declared In

CCNode.h

  positionInPoints

Position (x,y) of the node in points from the bottom left corner.

@property (nonatomic, readwrite, assign) CGPoint positionInPoints

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

Declared In

CCNode.h

Rotation and Skew

  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 node clockwise.

@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 rotation performing a horizontal rotational skew.

@property (nonatomic, readwrite, assign) float rotationalSkewX

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 rotation performing a vertical rotational skew.

@property (nonatomic, readwrite, assign) float rotationalSkewY

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

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

Declared In

CCNode.h

Scale

  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.

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.

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.

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.

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.

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.

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

Declared In

CCNode.h

Size

  contentSize

The untransformed size of the node in the unit specified by contentSizeType property. The contentSize remains the same regardless of whether the node is scaled or rotated.

@property (nonatomic, readwrite, assign) CGSize contentSize

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

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

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

– boundingBox

Returns an axis aligned bounding box in points, in the parent node’s coordinate system.

- (CGRect)boundingBox

Declared In

CCNode.h

Content Anchor

  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.

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.

Declared In

CCNode.h

Working with Node Trees

– 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.

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.

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.

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 node from the screen.

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 node from the screen.

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

– 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

  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

  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

  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 a node that already is in the scene.

See Also

Declared In

CCNode.h

Removing Nodes without stopping Actions/Scheduling (unsafe!)

– 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 the node hierarchy at some point, or send it the cleanup method when you no longer need the node (for instance before switching scenes).

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 the node hierarchy at some point, or send it the cleanup method when you no longer need the node (for instance before switching scenes).

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 the node hierarchy at some point, or send it the cleanup method when you no longer need the node (for instance before switching scenes).

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 node hierarchy at some point, or send them the cleanup method when you no longer need the children (for instance before switching scenes).

Declared In

CCNode.h

Naming Nodes

  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

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

Declared In

CCNode.h

Working with Actions

  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

  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

– 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

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

– stopAction:

Removes an action from the running action list.

- (void)stopAction:(CCAction *)action

Parameters

action

Action to remove.

See Also

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

– 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

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

CocosBuilder Animation Manager

  animationManager

Returns the Animation Manager of this node, or that of its parent.

@property (nonatomic, assign, readwrite) CCAnimationManager *animationManager

Discussion

Note: The animationManager property is nil during a node’s init methods.

Declared In

CCNode.h

Scheduling Selectors and Blocks

– 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

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 selector name. 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

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 selector name. 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

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 selector name. 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

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 selector name. 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

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

Transforms and Matrices

– 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

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

Declared In

CCNode.h

– nodeToWorldTransform

Returns the world affine transform matrix. The matrix is in Pixels.

- (CGAffineTransform)nodeToWorldTransform

Declared In

CCNode.h

– worldToNodeTransform

Returns the inverse world affine transform matrix. The matrix is in Pixels.

- (CGAffineTransform)worldToNodeTransform

Declared In

CCNode.h

Converting Point and Size "Types"

– 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.

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.

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.

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

Declared In

CCNode.h

Converting to and from the Node's Coordinate System

– 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

– 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

– 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

– 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

– 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

Visibility and Draw Order

  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 set node.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

Color

  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.

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.

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

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

Declared In

CCNode.h

Opacity (Alpha)

  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

  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

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

Declared In

CCNode.h

Rendering (Implemented in Subclasses)

– 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 CCRenderer documentation.

Warning: You must not call [super draw:transform:];

See Also

Declared In

CCNode.h

Scene Management (Implemented in Subclasses)

– 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.

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

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.

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

Declared In

CCNode.h

Physics Body

  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

Declared In

CCNode.h

– hasDefaultShaderUniforms

Returns true if the node is not using custom uniforms.

- (BOOL)hasDefaultShaderUniforms

Declared In

CCNode.h

  renderState

Cache and return the current render state. Should be set to nil whenever changing a property that affects the renderstate.

@property (nonatomic, strong) CCRenderState *renderState

Declared In

CCNode.h

– detachChild:cleanup:

  • performs OpenGL view-matrix transformation of its ancestors.
- (void)detachChild:(CCNode *)child cleanup:(BOOL)doCleanup

Declared In

CCNode.h

Debug Methods

– walkSceneGraph:

Prints on the debug console the scene graph

- (void)walkSceneGraph:(NSUInteger)level

Parameters

level

Level of debug information.

Declared In

CCNode+Debug.h