Основные API узлов и компонентов
Мы узнали, как получить доступ к экземплярам узлов и компонентов с предыдущей статьи Доступ к узлу и другим компонентам. Теперь мы рассмотрим полезные API узлов и компонентов. Эта статья работает совместно с cc.Node и cc.Component ссылка на API.
Состояние и иерархия узла.
Предположим, что мы находимся на скрипте компонента и используем this.node
для доступа к текущему узлу.
Активация/деактивация узла
this.node.active = false;
Операция деактивации узла позволяет:
- Скрыть текущий узел и все дочерние узлы в сцене.
- Отключить все компоненты на текущем узле и все дочерние узлы, что означает, что метод
update
в этих компонентах не будет вызываться. - Если в этих компонентах есть метод
onDisable
, он будет вызван.
this.node.active = true;
Операция активации узла позволяет:
- Показывать текущий узел и все дочерние узлы в сцене, если дочерний узел не деактивирован отдельно.
- Включить все компоненты на текущем узле и все дочерние узлы, что означает, что метод
update
в этих компонентах будет вызываться в каждом кадре. - Если в этих компонентах существует метод
onEnable
, он будет вызван.
Change node's parent
Assume the parent node is parentNode
, child node is this.node
You can do:
this.node.parent = parentNode;
or
this.node.removeFromParent(false);
parentNode.addChild(this.node);
These two method have equal effect.
Notice:
removeFromParent
usually need to pass afalse
, otherwise it will clear all the events and actions on the node.- creating a new node with Creating and Destroying Nodes section, you'll need to give the newly created node a parent to initialize it properly.
Access child node
this.node.children
will return all child nodes of current node.
this.node.childrenCount
will return the number of child nodes.
Notice the above API will only count direct children, not grand children.
Update node transform (position, rotation, scale, size)
Position
You can assign value to x
and y
:
this.node.x = 100;
this.node.y = 50;
or use setPosition
method:
this.node.setPosition(100, 50);
this.node.setPosition(cc.v2(100, 50));
or set position
value:
this.node.position = cc.v2(100, 50);
All above will give you the same result.
Rotation
this.node.rotation = 90;
or
this.node.setRotation(90);
Scale
this.node.scaleX = 2;
this.node.scaleY = 2;
or
this.node.setScale(2);
this.node.setScale(2, 2);
If you pass only one parameter to setScale
, both scaleX
and scaleY
will be changed.
Size(width and height)
this.node.setContentSize(100, 100);
this.node.setContentSize(cc.v2(100, 100));
or
this.node.width = 100;
this.node.height = 100;
Anchor Point
this.node.anchorX = 1;
this.node.anchorY = 0;
or
this.node.setAnchorPoint(1, 0);
All above transform changes will affect renderer component on the node, such as Sprite and Label.
Color and Opacity
When using basic renderer component like Sprite and Label, make sure you change the color or opacity on the node, since these API are taken out of components.
If we have a Sprite instance mySprite
, to change its color:
mySprite.node.color = cc.Color.RED;
opacity:
mySprite.node.opacity = 128;
Useful common component API
cc.Component
is the base class for all components, so we can use all the following API (in the component script this
is the instance of component):
this.node
: The node instance current component is attached to.this.enabled
: When set to true, theupdate
method will be called each frame, for renderer components this can be used as a display switch.update(dt)
: As a member method of component, will be called each frame whenenabled
property is set totrue
.onLoad()
: Will be called when the component is first loaded and initialized (when the node is inserted into the node tree)start()
: Will be called before the firstupdate
run, usually used to initialize some logic which need to be called after all components'onload
methods called.
More details about component member method please read Life Cycle Callbacks.