创建和销毁节点

创建新节点

除了通过场景编辑器创建节点外,我们也可以在脚本中动态创建节点。通过 new cc.Node() 并将它加入
到场景中,可以实现整个创建过程。

以下是一个简单的例子:

  1. cc.Class({
  2. extends: cc.Component,
  3. properties: {
  4. sprite: {
  5. default: null,
  6. type: cc.SpriteFrame,
  7. },
  8. },
  9. start: function () {
  10. var node = new cc.Node('sprite ' + this.count);
  11. var sp = node.addComponent(cc.Sprite);
  12. sp.spriteFrame = this.sprite;
  13. node.parent = this.node;
  14. node.setPosition(0,0);
  15. },
  16. });

克隆已有节点

有时我们希望动态的克隆场景中的已有节点,我们可以通过 cc.instantiate 方法完成。使用方法如下:

  1. cc.Class({
  2. extends: cc.Component,
  3. properties: {
  4. target: {
  5. default: null,
  6. type: cc.Node,
  7. },
  8. },
  9. start: function () {
  10. var scene = cc.director.getScene();
  11. var node = cc.instantiate(this.target);
  12. node.parent = scene;
  13. node.setPosition(0,0);
  14. },
  15. });

创建预置节点

和克隆已有节点相似,你也设置你的预置(prefab)节点并通过 cc.instantiate 生成。使用方法如下:

  1. cc.Class({
  2. extends: cc.Component,
  3. properties: {
  4. target: {
  5. default: null,
  6. type: cc.Prefab,
  7. },
  8. },
  9. start: function () {
  10. var scene = cc.director.getScene();
  11. var node = cc.instantiate(this.target);
  12. node.parent = scene;
  13. node.setPosition(0,0);
  14. },
  15. });

销毁节点

通过 node.destroy() 函数,可以销毁节点。值得一提的是,销毁节点并不会立刻发生,而是在当前
帧逻辑更新结束后,统一执行。当一个节点销毁后,该节点就处于无效状态,可以通过 cc.isValid 判断
当前节点是否已经被销毁。

使用方法如下:

  1. cc.Class({
  2. extends: cc.Component,
  3. properties: {
  4. target: cc.Node,
  5. },
  6. start: function () {
  7. setTimeout(function () {
  8. this.target.destroy();
  9. }.bind(this), 5000);
  10. },
  11. update: function (dt) {
  12. if ( !cc.isValid(this.target) ) {
  13. this.enabled = false;
  14. return;
  15. }
  16. this.target.rotation += dt * 10.0;
  17. },
  18. });

继续前往 发射和监听事件 说明文档。