cocosCreator版本: 3.7
cocosCreator的工作流程是通过节点–组件来实现的,节点作为场景中的基本单位, 而不同功能的组件挂载在节点之上,来完成页面的搭建。
比如Canvas
节点的组成组件部分:
在cocosCreator中,脚本也可以作为组件嵌入到节点中。每个不同功能的节点都是由各种组件组成。
比如,Sprite
节点的组成组件部分:
比如,Button
节点的组成组件部分:
简单的理解就如官方文档所说: 场景由多个节点构成,节点作为实体,不同功能的组件挂载到节点上。参考:节点和组件
在组件脚本中,访问当前脚本的所在节点,我们可以使用通过this.node
访问。
基本属性:
postion
节点位置相关,使用方法:// 通过接口方法使用
this.node.setPosition(100, 50, 0);
this.node.setPosition(new Vec3(100, 50, 0));
// 通过变量使用
this.node.position = new Vec3(100, 50, 0);
rotation
节点旋转相关,使用方法:this.node.setRotationFromEuler(90, 0, 0);
scale
节点缩放相关,使用方法:this.node.setScale(2, 2, 2);
常用属性:
this.node.active = true; // 激活节点
this.node.active = false; //
激活后的节点,该节点和所有子节点上的组件都会被启用
// 通常用于检测节点是否销毁的判定
let isValid = this.node.isValid;
let children = this.node.children; // 获取子节点的数组相关,不包含子节点的子节点
let length = this.node.children.length; // 获取子节点的数量
// 父节点为parentNode, 子节点为this.node
// 方法1
this.node.parent = parentNode;
// 方法2, 注意removeFromParent的参数要为false, 否则会清空节点上绑定的事件和action等
this.node.removeFromParent(false);
parentNode.addChild(this.node);
let node = new Node("Box");
node.setPostion(0, 0, 0);
// 创建的节点不会主动添加到场景中,需要手动添加
director.getScene().addChild(node);
instantiate
@property(Node)
private bulletNode: Node = null;start() {let scene = director.getScene();let newNode = instantiate(bulletNode);newNode.setPosition(0, 0, 0);scene.addChild(newNode);
}
关于克隆节点相关,也可以通过预制体来构建
@property({type: Prefab})
private bulletNode: Prefab = null; start() {// ...
}
// 使用this.node.destory()
// 它并不是立即被移除,而是在当前帧逻辑更新结束后,执行
this.node.destory()
注意:destory
和removeFromParent
二者相比, 后者并不会从内从中释放,引擎内部仍会持有它的数据。
如果一个节点不再使用,就调用它的destory
就可以了,否则会导致内存泄漏。
脚本访问同节点下的其他组件可使用接口:getComponent
// 访问该组件所在的节点
let curNode = this.node; // 访问该节点下下的组件, 脚本也作为组件,使用脚本的名字即可
let label = this.node.getComponent(Label);
let script = this.node.getComponent("MainScene");
脚本访问其他节点或组件, 一般通过属性检查器和Property
来设定,比如:
@property({type: Button, tooltip: "这是一个按钮"})
public backBtn: Button = null!;start() {this.backBtn.position = new Vec3(0, 0, 0);
}
更多参考:访问节点和其他组件
cocosCreator中的组件主要由两大类:
2D渲染组件主要有:
UI组件主要有:
继承于Componet
的类都被称为组件类,其对象被称为组件。需要注意的是:组件的不能由构造函数创建,必须通过节点来创建,这样节点就能够操控组件的生命周期。
@ccclass("MyComponent")
class MyComponent extends Component {//
}// 创建组件
const componet = this.node.addComponent(MyComponent);
// 销毁组件
this.node.removeComponet(MyComponet);
同一节点上的组件执行顺序按照属性检查器来的排列顺序从上到下的执行, 可以通过齿轮按钮的向上移动/向下移动
来控制。
如果使用脚本控制的话,可以使用executionOrder
来设定,比如:
import { _decorator, Component, Button} from 'cc';
const { ccclass, property, executionOrder} = _decorator;@ccclass('mainScene')
// 数值越小,越先执行。默认为0
// 仅对onLoad, onEnable, start, update, lateUpdate有效, 对onDisable, onDestory无效
@executionOrder(-1)
export class mainScene extends Component {
}
详情参考:组件和组件执行顺序