Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Node

!#en Class of all entities in Cocos Creator scenes. Basic functionalities include:

  • Hierarchy management with parent and children
  • Components management
  • Coordinate system with position, scale, rotation in 3d space !#zh Cocos Creator 场景中的所有节点类。 基本特性有:
  • 具有层级关系
  • 持有各类组件
  • 维护 3D 空间左边变换(坐标、旋转、缩放)信息

Hierarchy

Implements

Index

Constructors

Properties

Accessors

Methods

Constructors

constructor

  • newNode(name?: undefined | string): Node

Properties

Protected _active

_active: boolean = true

Protected _activeInHierarchy

_activeInHierarchy: boolean = false

Protected _children

_children: this[] = []

Protected _components

_components: Component[] = []

Protected _dirtyFlags

_dirtyFlags: TransformBit = TransformBit.NONE

Protected _euler

_euler: Vec3 = new Vec3()

Protected _eulerDirty

_eulerDirty: boolean = false

Protected _eventMask

_eventMask: number = 0

Protected _eventProcessor

_eventProcessor: NodeEventProcessor = new NodeEventProcessor(this)

Protected _id

_id: string = idGenerator.getNewId()

Protected _layer

_layer: number = Layers.Enum.DEFAULT

Protected _lpos

_lpos: Vec3 = new Vec3()

Protected _lrot

_lrot: Quat = new Quat()

Protected _lscale

_lscale: Vec3 = new Vec3(1, 1, 1)

Protected _mat

_mat: Mat4 = new Mat4()

Protected _name

_name: string

_objFlags

_objFlags: number

Protected _parent

_parent: this | null = null

Protected _pos

_pos: Vec3 = new Vec3()

Protected _prefab

_prefab: any = null

Protected _registerIfAttached

_registerIfAttached: undefined | (Anonymous function) = !EDITOR ? undefined : function (this: BaseNode, register) {if (EditorExtends.Node && EditorExtends.Component) {if (register) {EditorExtends.Node.add(this._id, this);for (let i = 0; i < this._components.length; i++) {const comp = this._components[i];EditorExtends.Component.add(comp._id, comp);}}else {for (let i = 0; i < this._components.length; i++) {const comp = this._components[i];EditorExtends.Component.remove(comp._id);}EditorExtends.Node.remove(this._id);}}const children = this._children;for (let i = 0, len = children.length; i < len; ++i) {const child = children[i];child._registerIfAttached!(register);}}

Protected _rot

_rot: Quat = new Quat()

Protected _scale

_scale: Vec3 = new Vec3(1, 1, 1)

Protected _scene

_scene: any = NullScene

Protected _siblingIndex

_siblingIndex: number = 0

_static

_static: boolean = false

_uiProps

_uiProps: NodeUIProperties = new NodeUIProperties(this)

Static EventType

EventType: SystemEventType = SystemEventType

Event types emitted by Node

Static NodeSpace

NodeSpace: NodeSpace = NodeSpace

Coordinates space

Static TransformBit

TransformBit: TransformBit = TransformBit

Bit masks for Node transformation parts, can be used to determine which part changed in SystemEventType.TRANSFORM_CHANGED event

Static TransformDirtyBit

TransformDirtyBit: TransformBit = TransformBit

Bit masks for Node transformation parts

deprecated

please use Node.TransformBit

Static Protected _stackId

_stackId: number = 0

Static Protected _stacks

_stacks: Array<Array<null | BaseNode>> = [[]]

Static bookOfChange

bookOfChange: Map<string, number> = bookOfChange

Static Protected idGenerator

idGenerator: IDGenerator = idGenerator

Accessors

Protected persistNode

  • get persistNode(): boolean
  • set persistNode(value: boolean): void
  • If true, the node is an persist node which won't be destroyed during scene transition. If false, the node will be destroyed automatically when loading a new scene. Default is false.

    default

    false

    Returns boolean

  • If true, the node is an persist node which won't be destroyed during scene transition. If false, the node will be destroyed automatically when loading a new scene. Default is false.

    default

    false

    Parameters

    • value: boolean

    Returns void

active

  • get active(): boolean
  • set active(isActive: boolean): void
  • The local active state of this node. Note that a Node may be inactive because a parent is not active, even if this returns true. Use activeInHierarchy if you want to check if the Node is actually treated as active in the scene.

    default

    true

    Returns boolean

  • The local active state of this node. Note that a Node may be inactive because a parent is not active, even if this returns true. Use activeInHierarchy if you want to check if the Node is actually treated as active in the scene.

    default

    true

    Parameters

    • isActive: boolean

    Returns void

activeInHierarchy

  • get activeInHierarchy(): boolean

children

  • get children(): this[]

components

eulerAngles

  • get eulerAngles(): {}
  • set eulerAngles(val: Readonly<Vec3>): void

eventProcessor

  • get eventProcessor(): NodeEventProcessor

forward

  • get forward(): Vec3
  • set forward(dir: Vec3): void

hasChangedFlags

  • get hasChangedFlags(): number
  • set hasChangedFlags(val: number): void

isValid

  • get isValid(): boolean
  • Indicates whether the object is not yet destroyed. (It will not be available after being destroyed)
    When an object's destroy is called, it is actually destroyed after the end of this frame. So isValid will return false from the next frame, while isValid in the current frame will still be true. If you want to determine whether the current frame has called destroy, use isValid(obj, true), but this is often caused by a particular logical requirements, which is not normally required.

    default

    true

    readonly
    example
    import { Node, log } from 'cc';
    const node = new Node();
    log(node.isValid);    // true
    node.destroy();
    log(node.isValid);    // true, still valid in this frame
    // after a frame...
    log(node.isValid);    // false, destroyed in the end of last frame

    Returns boolean

layer

  • get layer(): number
  • set layer(l: number): void

matrix

  • set matrix(val: Readonly<Mat4>): void

name

  • get name(): string
  • set name(value: string): void

parent

  • get parent(): null | this
  • set parent(value: null | this): void

position

  • get position(): Readonly<Vec3>
  • set position(val: Readonly<Vec3>): void

rotation

  • get rotation(): Readonly<Quat>
  • set rotation(val: Readonly<Quat>): void

scale

  • get scale(): Readonly<Vec3>
  • set scale(val: Readonly<Vec3>): void

scene

  • get scene(): any

uuid

  • get uuid(): string

worldMatrix

  • get worldMatrix(): Readonly<Mat4>

worldPosition

  • get worldPosition(): Readonly<Vec3>
  • set worldPosition(val: Readonly<Vec3>): void

worldRotation

  • get worldRotation(): Readonly<Quat>
  • set worldRotation(val: Readonly<Quat>): void

worldScale

  • get worldScale(): Readonly<Vec3>
  • set worldScale(val: Readonly<Vec3>): void

Methods

Protected Optional checkMultipleComp

  • checkMultipleComp(constructor: Function): void
  • Ensures that this node has already had the specified component(s). If not, this method throws.

    throws

    If one or more component of same type have been existed in this node.

    Parameters

    • constructor: Function

      Constructor of the component.

    Returns void

destroyImmediate

  • _destroyImmediate(): void

destruct

  • _destruct(): void
  • Clear all references in the instance.

    NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. You can override the _destruct method if you need, for example: _destruct: function () { for (var key in this) { if (this.hasOwnProperty(key)) { switch (typeof this[key]) { case 'string': this[key] = ''; break; case 'object': case 'function': this[key] = null; break; } } }

    Returns void

Protected disableChildComps

  • _disableChildComps(): void

Protected instantiate

  • instantiate(cloned: any): any

onBatchCreated

  • _onBatchCreated(): void

onBatchRestored

  • _onBatchRestored(): void

onBeforeSerialize

  • _onBeforeSerialize(): void

Protected onHierarchyChanged

  • onHierarchyChanged(oldParent: this | null): void

Protected onHierarchyChangedBase

  • onHierarchyChangedBase(oldParent: this | null): void

onPostActivated

  • onPostActivated(active: boolean): void

Protected onPreDestroy

  • _onPreDestroy(): void

Protected onPreDestroyBase

  • _onPreDestroyBase(): boolean

onSetParent

  • onSetParent(oldParent: this | null, keepWorldTransform: boolean): void

Protected Optional onSiblingIndexChanged

  • onSiblingIndexChanged(siblingIndex: number): void

removeComponent

  • removeComponent(component: Component): void

updateSiblingIndex

  • _updateSiblingIndex(): void

addChild

  • addChild(child: this | Node): void

addComponent

  • Adds a component class to the node. You can also add component to node by passing in the name of the script.

    throws

    TypeError if the className does not specify a cc-class constructor extending the Component.

    example
    var test = node.addComponent("Test");

    Type parameters

    Parameters

    • classConstructor: Constructor<T>

      The class of the component to add

    Returns T

  • Adds a component class to the node. You can also add component to node by passing in the name of the script.

    throws

    TypeError if the className does not specify a cc-class constructor extending the Component.

    example
    var test = node.addComponent("Test");

    Parameters

    • className: string

      The class name of the component to add

    Returns Component

attr

  • attr(attrs: Object): void
  • Properties configuration function. All properties in attrs will be set to the node, when the setter of the node is available, the property will be set via setter function.

    example
    var attrs = { name: 'New Name', active: false };
    node.attr(attrs);

    Parameters

    • attrs: Object

      Properties to be set to node

    Returns void

destroy

  • destroy(): boolean

destroyAllChildren

  • destroyAllChildren(): void

dispatchEvent

  • dispatchEvent(event: Event): void

emit

  • emit(type: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void
  • Trigger an event directly with the event name and necessary arguments.

    example
    eventTarget.emit('fire', event);
    eventTarget.emit('fire', message, emitter);

    Parameters

    • type: string

      event type

    • Optional arg0: any
    • Optional arg1: any

      First argument in callback

    • Optional arg2: any

      Second argument in callback

    • Optional arg3: any

      Third argument in callback

    • Optional arg4: any

      Fourth argument in callback

    Returns void

getChildByName

  • getChildByName(name: string): null | this
  • Returns a child with the same name.

    example
    var child = node.getChildByName("Test Node");

    Parameters

    • name: string

      A name to find the child node.

    Returns null | this

    a CCNode object whose name equals to the input parameter

getChildByPath

  • getChildByPath(path: string): null | this
  • Returns a child with the given path.

    example
    var child = node.getChildByPath("subNode/Test Node");

    Parameters

    • path: string

      A path to find the child node.

    Returns null | this

    a Node object whose path equals to the input parameter

getChildByUuid

  • getChildByUuid(uuid: string): null | this

getComponent

  • getComponent<T>(classConstructor: Constructor<T>): T | null
  • getComponent(className: string): Component | null
  • Returns the component of supplied type if the node has one attached, null if it doesn't. You can also get component in the node by passing in the name of the script.

    example
    // get custom test class.
    var test = node.getComponent("Test");

    Type parameters

    Parameters

    • classConstructor: Constructor<T>

      The class of the target component

    Returns T | null

  • Returns the component of supplied type if the node has one attached, null if it doesn't. You can also get component in the node by passing in the name of the script.

    example
    // get custom test class.
    var test = node.getComponent("Test");

    Parameters

    • className: string

      The class name of the target component

    Returns Component | null

getComponentInChildren

  • getComponentInChildren<T>(classConstructor: Constructor<T>): T | null
  • getComponentInChildren(className: string): Component | null

getComponents

  • getComponents<T>(classConstructor: Constructor<T>): T[]
  • getComponents(className: string): Component[]

getComponentsInChildren

  • getComponentsInChildren<T>(classConstructor: Constructor<T>): T[]
  • getComponentsInChildren(className: string): Component[]

getParent

  • getParent(): null | this

getPosition

  • Get position in local coordinate system, please try to pass out vector and reuse it to avoid garbage.

    Parameters

    • Optional out: Vec3

      Set the result to out vector

    Returns Vec3

    If out given, the return value equals to out, otherwise a new vector will be generated and return

getRotation

  • Get rotation as quaternion in local coordinate system, please try to pass out quaternion and reuse it to avoid garbage.

    Parameters

    • Optional out: Quat

      Set the result to out quaternion

    Returns Quat

    If out given, the return value equals to out, otherwise a new quaternion will be generated and return

getScale

  • Get scale in local coordinate system, please try to pass out vector and reuse it to avoid garbage.

    Parameters

    • Optional out: Vec3

      Set the result to out vector

    Returns Vec3

    If out given, the return value equals to out, otherwise a new vector will be generated and return

getSiblingIndex

  • getSiblingIndex(): number

getWorldMatrix

  • Get a world transform matrix

    Parameters

    • Optional out: Mat4

      Set the result to out matrix

    Returns Mat4

    If out given, the return value equals to out, otherwise a new matrix will be generated and return

getWorldPosition

  • Get position in world coordinate system, please try to pass out vector and reuse it to avoid garbage.

    Parameters

    • Optional out: Vec3

      Set the result to out vector

    Returns Vec3

    If out given, the return value equals to out, otherwise a new vector will be generated and return

getWorldRS

  • Get a world transform matrix with only rotation and scale

    Parameters

    • Optional out: Mat4

      Set the result to out matrix

    Returns Mat4

    If out given, the return value equals to out, otherwise a new matrix will be generated and return

getWorldRT

  • Get a world transform matrix with only rotation and translation

    Parameters

    • Optional out: Mat4

      Set the result to out matrix

    Returns Mat4

    If out given, the return value equals to out, otherwise a new matrix will be generated and return

getWorldRotation

  • Get rotation as quaternion in world coordinate system, please try to pass out quaternion and reuse it to avoid garbage.

    Parameters

    • Optional out: Quat

      Set the result to out quaternion

    Returns Quat

    If out given, the return value equals to out, otherwise a new quaternion will be generated and return

getWorldScale

  • Get scale in world coordinate system, please try to pass out vector and reuse it to avoid garbage.

    Parameters

    • Optional out: Vec3

      Set the result to out vector

    Returns Vec3

    If out given, the return value equals to out, otherwise a new vector will be generated and return

hasEventListener

  • hasEventListener(type: string, callback?: Function, target?: Object): boolean
  • Checks whether the EventTarget object has any callback registered for a specific type of event.

    Parameters

    • type: string

      The type of event.

    • Optional callback: Function

      The callback function of the event listener, if absent all event listeners for the given type will be removed

    • Optional target: Object

      The callback callee of the event listener

    Returns boolean

    True if a callback of the specified type is registered; false otherwise.

insertChild

  • insertChild(child: this | Node, siblingIndex: number): void
  • Inserts a child to the node at a specified index.

    example
    node.insertChild(child, 2);

    Parameters

    • child: this | Node

      the child node to be inserted

    • siblingIndex: number

      the sibling index to place the child in

    Returns void

invalidateChildren

  • Invalidate the world transform information for this node and all its children recursively

    Parameters

    • dirtyBit: TransformBit

      The dirty bits to setup to children, can be composed with multiple dirty bits

    Returns void

inverseTransformPoint

  • Inversely transform a point from world coordinate system to local coordinate system.

    Parameters

    • out: Vec3

      The result point in local coordinate system will be stored in this vector

    • p: Vec3

      A position in world coordinate system

    Returns Vec3

isChildOf

  • isChildOf(parent: this | Scene | null): boolean

lookAt

  • Set the orientation of the node to face the target position, the node is facing minus z direction by default

    Parameters

    • pos: Vec3

      Target position

    • Optional up: Vec3

      Up direction

    Returns void

off

  • off(type: string, callback?: Function, target?: Object, useCapture?: any): void
  • Removes the callback previously registered with the same type, callback, target and or useCapture. This method is merely an alias to removeEventListener.

    example
    this.node.off(SystemEventType.TOUCH_START, this.memberFunction, this);
    node.off(SystemEventType.TOUCH_START, callback, this.node);

    Parameters

    • type: string

      A string representing the event type being removed.

    • Optional callback: Function

      The callback to remove.

    • Optional target: Object

      The target (this object) to invoke the callback, if it's not given, only callback without target will be removed

    • Default value useCapture: any = false

      When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.

    Returns void

on

  • on(type: string | SystemEventType, callback: Function, target?: Object, useCapture?: any): void
  • Register a callback of a specific event type on Node. Use this method to register touch or mouse event permit propagation based on scene graph, These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:

    1. Capturing phase: dispatch in capture targets (_getCapturingTargets), e.g. parents in node tree, from root to the real target
    2. At target phase: dispatch to the listeners of the real target
    3. Bubbling phase: dispatch in bubble targets (_getBubblingTargets), e.g. parents in node tree, from the real target to root In any moment of the dispatching process, it can be stopped via event.stopPropagation() or event.stopPropagationImmidiate(). It's the recommended way to register touch/mouse event for Node, please do not use eventManager directly for Node. You can also register custom event and use emit to trigger custom event on Node. For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node. You can also pass event callback parameters with emit by passing parameters after type.
    example
    this.node.on(SystemEventType.TOUCH_START, this.memberFunction, this);  // if "this" is component and the "memberFunction" declared in CCClass.
    node.on(SystemEventType.TOUCH_START, callback, this);
    node.on(SystemEventType.TOUCH_MOVE, callback, this);
    node.on(SystemEventType.TOUCH_END, callback, this);

    Parameters

    • type: string | SystemEventType

      A string representing the event type to listen for.
      See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.

    • callback: Function

      The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique).

    • Optional target: Object

      The target (this object) to invoke the callback, can be null

    • Default value useCapture: any = false

      When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.

    Returns void

    • Just returns the incoming callback so you can save the anonymous function easier.

once

  • once(type: string, callback: Function, target?: Object, useCapture?: any): void
  • Register an callback of a specific event type on the Node, the callback will remove itself after the first time it is triggered.

    Parameters

    • type: string

      A string representing the event type to listen for.

    • callback: Function

      The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique).

    • Optional target: Object

      The target (this object) to invoke the callback, can be null

    • Optional useCapture: any

    Returns void

pauseSystemEvents

  • pauseSystemEvents(recursive: boolean): void

removeAllChildren

  • removeAllChildren(): void

removeChild

  • removeChild(child: this | Node): void

removeComponent

  • removeComponent<T>(classConstructor: Constructor<T>): void
  • removeComponent(classNameOrInstance: string | Component): void
  • Removes a component identified by the given name or removes the component object given. You can also use component.destroy() if you already have the reference.

    deprecated

    please destroy the component to remove it.

    example
    import { Sprite } from 'cc';
    const sprite = node.getComponent(Sprite);
    if (sprite) {
        node.removeComponent(sprite);
    }
    node.removeComponent('Sprite');

    Type parameters

    Parameters

    • classConstructor: Constructor<T>

      The class of the component to remove

    Returns void

  • Removes a component identified by the given name or removes the component object given. You can also use component.destroy() if you already have the reference.

    deprecated

    please destroy the component to remove it.

    example
    import { Sprite } from 'cc';
    const sprite = node.getComponent(Sprite);
    if (sprite) {
        node.removeComponent(sprite);
    }
    node.removeComponent('Sprite');

    Parameters

    • classNameOrInstance: string | Component

      The class name of the component to remove or the component instance to be removed

    Returns void

removeFromParent

  • removeFromParent(): void

resumeSystemEvents

  • resumeSystemEvents(recursive: boolean): void

rotate

setParent

  • setParent(value: this | null, keepWorldTransform?: boolean): void
  • Set parent of the node.

    Parameters

    • value: this | null

      Parent node

    • Default value keepWorldTransform: boolean = false

      Whether keep node's current world transform unchanged after this operation

    Returns void

setPosition

  • setPosition(position: Vec3): void
  • setPosition(x: number, y: number, z: number): void

setRTS

setRotation

  • setRotation(rotation: Quat): void
  • setRotation(x: number, y: number, z: number, w: number): void
  • Set rotation in local coordinate system with a quaternion representing the rotation

    Parameters

    • rotation: Quat

      Rotation in quaternion

    Returns void

  • Set rotation in local coordinate system with a quaternion representing the rotation

    Parameters

    • x: number

      X value in quaternion

    • y: number

      Y value in quaternion

    • z: number

      Z value in quaternion

    • w: number

      W value in quaternion

    Returns void

setRotationFromEuler

  • setRotationFromEuler(x: number, y: number, z: number): void
  • Set rotation in local coordinate system with euler angles

    Parameters

    • x: number

      X axis rotation

    • y: number

      Y axis rotation

    • z: number

      Z axis rotation

    Returns void

setScale

  • setScale(scale: Vec3): void
  • setScale(x: number, y: number, z: number): void

setSiblingIndex

  • setSiblingIndex(index: number): void

setWorldPosition

  • setWorldPosition(position: Vec3): void
  • setWorldPosition(x: number, y: number, z: number): void

setWorldRotation

  • setWorldRotation(rotation: Quat): void
  • setWorldRotation(x: number, y: number, z: number, w: number): void
  • Set rotation in world coordinate system with a quaternion representing the rotation

    Parameters

    • rotation: Quat

      Rotation in quaternion

    Returns void

  • Set rotation in world coordinate system with a quaternion representing the rotation

    Parameters

    • x: number

      X value in quaternion

    • y: number

      Y value in quaternion

    • z: number

      Z value in quaternion

    • w: number

      W value in quaternion

    Returns void

setWorldRotationFromEuler

  • setWorldRotationFromEuler(x: number, y: number, z: number): void
  • Set rotation in world coordinate system with euler angles

    Parameters

    • x: number

      X axis rotation

    • y: number

      Y axis rotation

    • z: number

      Z axis rotation

    Returns void

setWorldScale

  • setWorldScale(scale: Vec3): void
  • setWorldScale(x: number, y: number, z: number): void

targetOff

  • targetOff(target: string | Object): void

translate

updateWorldTransform

  • updateWorldTransform(): void

walk

  • walk(preFunc: (target: this) => void, postFunc?: undefined | ((target: this) => void)): void
  • Walk though the sub children tree of the current node. Each node, including the current node, in the sub tree will be visited two times, before all children and after all children. This function call is not recursive, it's based on stack. Please don't walk any other node inside the walk process.

    example
    node.walk(function (target) {
        console.log('Walked through node ' + target.name + ' for the first time');
    }, function (target) {
        console.log('Walked through node ' + target.name + ' after walked all children in its sub tree');
    });

    Parameters

    • preFunc: (target: this) => void

      The callback to process node when reach the node for the first time

        • (target: this): void
        • Parameters

          • target: this

          Returns void

    • Optional postFunc: undefined | ((target: this) => void)

      The callback to process node when re-visit the node after walked all children in its sub tree

    Returns void

Static deferredDestroy

  • _deferredDestroy(): void

Static Protected findChildComponent

  • findChildComponent(children: BaseNode[], constructor: any): any

Static Protected findChildComponents

  • findChildComponents(children: BaseNode[], constructor: any, components: any): void

Static Protected findComponent

Static Protected findComponents

  • findComponents(node: BaseNode, constructor: Function, components: Component[]): void

Static setScene

Static isNode

  • isNode(obj: object | null): obj is Node

Generated using TypeDoc