节点默认是激活的。除了在编辑器中切换节点的激活、关闭状态,也可以通过以下代码:
this.node.active = true;
假设父节点为 parentNode
,子节点为 this.node
this.node.parent = parentNode;
或
this.node.removeFromParent(false);
parentNode.addChild(this.node);
更改节点的变换(位置、旋转、缩放、尺寸)
更改节点位置
分别对 x 轴和 y 轴坐标赋值:
this.node.x = 100;
this.node.y = 50;
使用 setPosition
方法:
this.node.setPosition(100, 50);
this.node.setPosition(cc.v2(100, 50));
设置 position
变量:
this.node.position = cc.v2(100, 50);
以上两种用法等价。
更改节点旋转
this.node.rotation = 90;
或
this.node.setRotation(90);
更改节点缩放
this.node.scaleX = 2;
this.node.scaleY = 2;
或
this.node.setScale(2);
this.node.setScale(2, 2);
以上两种方法等价。setScale
传入单个参数时,会同时修改 scaleX
和 scaleY
。
更改节点尺寸
this.node.setContentSize(100, 100);
this.node.setContentSize(cc.size(100, 100));
或
this.node.width = 100;
this.node.height = 100;
以上两种方式等价。
更改节点锚点位置
this.node.anchorX = 1;
this.node.anchorY = 0;
或
this.node.setAnchorPoint(1, 0);
注意以上这些修改变换的方法会影响到节点上挂载的渲染组件,比如 Sprite 图片的尺寸、旋转等等。
颜色和不透明度
在使用 Sprite, Label 这些基本的渲染组件时,要注意修改颜色和不透明度的操作只能在节点的实例上进行,因为这些渲染组件本身并没有设置颜色和不透明度的接口。
假如我们有一个 Sprite 的实例为 mySprite
,如果需要设置它的颜色:
mySprite.node.color = cc.Color.RED;
设置不透明度:
mySprite.node.opacity = 128;
常用组件接口
cc.Component
是所有组件的基类,任何组件都包括如下的常见接口(假设我们在该组件的脚本中,以 this 指代本组件):
this.node
:该组件所属的节点实例this.enabled
:是否每帧执行该组件的update
方法,同时也用来控制渲染组件是否显示update(dt)
:作为组件的成员方法,在组件的enabled
属性为true
时,其中的代码会每帧执行onLoad()
:组件所在节点进行初始化时(节点添加到节点树时)执行start()
:会在该组件第一次update
之前执行,通常用于需要在所有组件的onLoad
初始化完毕后执行的逻辑