Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Node

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: any = new legacyCC.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 _poolHandle

_poolHandle: NodeHandle = NULL_HANDLE

Protected _pos

_pos: Vec3 = new Vec3()

Protected _prefab

_prefab: PrefabInfo | null = null

Protected _registerIfAttached

_registerIfAttached: undefined | _registerIfAttached = !EDITOR ? undefined : function _registerIfAttached (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: Scene = null!

Protected _siblingIndex

_siblingIndex: number = 0

_static

_static: boolean = false

_uiProps

_uiProps: NodeUIProperties = new NodeUIProperties(this)

Static EventType

EventType: SystemEventType = SystemEventType

节点可能发出的事件类型

Static NodeSpace

NodeSpace: NodeSpace = NodeSpace

空间变换操作的坐标系

Static TransformBit

TransformBit: TransformBit = TransformBit

节点变换更新的具体部分,可用于判断 SystemEventType.TRANSFORM_CHANGED 事件的具体类型

Static TransformDirtyBit

TransformDirtyBit: TransformBit = TransformBit

节点变换更新的具体部分

deprecated

please use Node.TransformBit

Static Protected _stackId

_stackId: number = 0

Static Protected _stacks

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

Static bookOfChange

bookOfChange: Map<Node, number> = bookOfChange

Static Protected idGenerator

idGenerator: IDGenerator = idGenerator

Accessors

Protected persistNode

  • get persistNode(): boolean
  • set persistNode(value: boolean): void
  • 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。 如果为false,节点将在加载新场景时自动销毁。默认为 false。

    default

    false

    Returns boolean

  • 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。 如果为false,节点将在加载新场景时自动销毁。默认为 false。

    default

    false

    Parameters

    • value: boolean

    Returns void

active

  • get active(): boolean
  • set active(isActive: boolean): void
  • 当前节点的自身激活状态。 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。 如果你想检查节点在场景中实际的激活状态可以使用 activeInHierarchy

    default

    true

    Returns boolean

  • 当前节点的自身激活状态。 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。 如果你想检查节点在场景中实际的激活状态可以使用 activeInHierarchy

    default

    true

    Parameters

    • isActive: boolean

    Returns void

activeInHierarchy

  • get activeInHierarchy(): boolean

angle

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

children

  • get children(): this[]

components

eulerAngles

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

eventProcessor

  • get eventProcessor(): any

forward

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

handle

  • get handle(): NodeHandle

hasChangedFlags

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

isValid

  • get isValid(): boolean
  • 表示该对象是否可用(被 destroy 后将不可用)。
    当一个对象的 destroy 调用以后,会在这一帧结束后才真正销毁。
    因此从下一帧开始 isValid 就会返回 false,而当前帧内 isValid 仍然会是 true。
    如果希望判断当前帧是否调用过 destroy,请使用 isValid(obj, true),不过这往往是特殊的业务需求引起的,通常情况下不需要这样。

    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

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<T>(constructor: Constructor<T>): 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 instantiate

  • instantiate(cloned: any, isSyncedNode: any): any

onBatchCreated

  • onBatchCreated(dontSyncChildPrefab: boolean): 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

Protected updateScene

  • _updateScene(): void

updateSiblingIndex

  • _updateSiblingIndex(): void

addChild

  • addChild(child: this | Node): void

addComponent

  • 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。

    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

  • 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。

    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: unknown): void
  • 属性配置函数。在 attrs 的所有属性将被设置为节点属性。

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

    Parameters

    • attrs: unknown

      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
  • 通过事件名发送自定义事件

    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
  • 通过名称获取节点的子节点。

    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
  • 通过路径获取节点的子节点。

    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
  • 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。 传入参数也可以是脚本的名称。

    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

  • 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。 传入参数也可以是脚本的名称。

    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

  • 获取本地坐标,注意,尽可能传递复用的 Vec3 以避免产生垃圾。

    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

  • 获取本地旋转,注意,尽可能传递复用的 Quat 以避免产生垃圾。

    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

  • 获取本地缩放,注意,尽可能传递复用的 Vec3 以避免产生垃圾。

    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

  • 获取世界变换矩阵

    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

  • 获取世界坐标,注意,尽可能传递复用的 Vec3 以避免产生垃圾。

    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

  • 获取只包含旋转和缩放的世界变换矩阵

    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

  • 获取只包含旋转和位移的世界变换矩阵

    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

  • 获取世界坐标系下的旋转,注意,尽可能传递复用的 Quat 以避免产生垃圾。

    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

  • 获取世界缩放,注意,尽可能传递复用的 Vec3 以避免产生垃圾。

    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?: AnyFunction, target?: unknown): any
  • 检查事件目标对象是否有为特定类型的事件注册的回调。

    Parameters

    • type: string

      The type of event.

    • Optional callback: AnyFunction

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

    • Optional target: unknown

      The callback callee of the event listener

    Returns any

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

insertChild

  • insertChild(child: this | Node, siblingIndex: number): void

invalidateChildren

inverseTransformPoint

  • 逆向变换一个空间点,一般用于将世界坐标转换到本地坐标系中。

    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

off

  • off(type: string, callback?: AnyFunction, target?: unknown, useCapture?: any): void
  • 删除之前与同类型,回调,目标或 useCapture 注册的回调。

    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: AnyFunction

      The callback to remove.

    • Optional target: unknown

      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: AnyFunction, target?: unknown, useCapture?: any): void
  • 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:

    1. 捕获阶段:派发事件给捕获目标(通过 _getCapturingTargets 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
    2. 目标阶段:派发给目标节点的监听器。
    3. 冒泡阶段:派发事件给冒泡目标(通过 _getBubblingTargets 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发直到根节点。 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 eventManager。 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器 你可以通过在 emit 方法调用时在 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/EventType/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.

    • callback: AnyFunction

      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: unknown

      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: AnyFunction, target?: unknown, useCapture?: any): void
  • 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。

    Parameters

    • type: string

      A string representing the event type to listen for.

    • callback: AnyFunction

      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: unknown

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

    • Optional useCapture: any

    Returns void

pauseSystemEvents

  • pauseSystemEvents(recursive: boolean): void
  • 暂停所有 SystemEvent 派发的系统事件。 如果传递 recursive 为 true,那么这个 API 将暂停本节点和它的子树上所有节点的节点系统事件。

    Parameters

    • recursive: boolean

      Whether pause system events recursively for the child node tree

    Returns void

removeAllChildren

  • removeAllChildren(): void

removeChild

  • removeChild(child: this | Node): void

removeComponent

  • removeComponent<T>(classConstructor: Constructor<T>): void
  • removeComponent(classNameOrInstance: string | Component): void
  • 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 如果你已经获得组件引用,你也可以直接调用 component.destroy()

    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

  • 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 如果你已经获得组件引用,你也可以直接调用 component.destroy()

    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
  • 恢复所有 SystemEvent 派发的系统事件。 如果传递 recursive 为 true,那么这个 API 将恢复本节点和它的子树上所有节点的节点系统事件。

    Parameters

    • recursive: boolean

      Whether resume system events recursively for the child node tree

    Returns void

rotate

setParent

  • setParent(value: this | null, keepWorldTransform?: boolean): void
  • 设置该节点的父节点。

    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?: undefined | number): void

setRTS

setRotation

  • setRotation(rotation: Quat): void
  • setRotation(x: number, y: number, z: number, w: number): void
  • 用四元数设置本地旋转

    Parameters

    • rotation: Quat

      Rotation in quaternion

    Returns void

  • 用四元数设置本地旋转

    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(rotation: Vec3): void
  • setRotationFromEuler(x: number, y: number, zOpt?: undefined | number): void

setScale

  • setScale(scale: Vec3): void
  • setScale(x: number, y: number, z?: undefined | 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
  • 用四元数设置世界坐标系下的旋转

    Parameters

    • rotation: Quat

      Rotation in quaternion

    Returns void

  • 用四元数设置世界坐标系下的旋转

    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
  • 用欧拉角设置世界坐标系下的旋转

    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 | unknown): void

translate

updateWorldTransform

  • updateWorldTransform(): void

walk

  • walk(preFunc: (target: this) => void, postFunc?: undefined | ((target: this) => void)): void
  • 遍历该节点的子树里的所有节点并按规则执行回调函数。 对子树中的所有节点,包含当前节点,会执行两次回调,preFunc 会在访问它的子节点之前调用,postFunc 会在访问所有子节点之后调用。 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。

    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

Static Protected findChildComponents

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

Static Protected findComponent

Static Protected findComponents

Static Protected setScene

Static isNode

  • isNode(obj: unknown): obj is Node

Generated using TypeDoc