微信小游戏MagnetGame开发(五)Prefab预制体的创建与销毁

版权声明:本博客属个人原创,转载请注明。 https://blog.csdn.net/qq_33198758/article/details/82190921

1. 预制体介绍

  游戏场景中左侧障碍物N、S磁铁1和右侧障碍物N、S磁铁2是在游戏中随机出现的。Player 3包含N、S两种状态,触摸屏幕后状态改变。这些都不是游戏一开始就加载的资源,我们称作预制体。
这里写图片描述

2. 预制体创建

第一步:

  首先找到层级管理器1处的”+”号,点击,选择新建空节点,将该节点命名为Myprefab。将资源管理器中的3北极图片拖动到Myprefab上,如2所示。
这里写图片描述

第二步:

  将Myprefab由层级管理器直接拖动到资源管理器下,如下图1所示。双击Myprefab,在2可以编辑该Myprefab属性,给它添加脚本等。
这里写图片描述

3. 预制体生成与销毁

  • 普通创建方法
 spawnNMagnetPlayer: function() {
        var scene = cc.director.getScene();
        var node = null;
        node = cc.instantiate(this.NMagnetPlayerPrefab); // 使用给定的prefab模板在场景中生成一个新节点
        node.parent = scene;
        node.setPosition(this.node.width/2,this.node.height/4);
    },
  • NodePool方法
      当prefab较多时,一般采用NodePool的方法,减少CPU负荷。具体方法如下图。先建立一个包含Prefab的NodePool,将Prefab添加到该NodePool中,当场景中需要创建NodePool时,用Get的方法获得一个Prefab,当游戏场景中需要销毁一个Prefab时,用Put的方法将Prefab放到NodePool当中
    这里写图片描述
    具体实现的代码为:
    先在onLoad函数中创建一个NodePool:
 onLoad () { 
       this.NMagnetPlayerPool = new cc.NodePool('NMagnetPlayer');
     },

  然后是创建与销毁:

spawnNMagnetPlayer: function() {   //创建一个Prefab
        var scene = cc.director.getScene();
        var node = null;
        // 使用给定的模板在场景中生成一个新节点
        if (this.NMagnetPlayerPool.size() > 0) {
            node = this.NMagnetPlayerPool.get(this); // 从NodePool中获得一个prefab
        } else {
            node = cc.instantiate(this.NMagnetPlayerPrefab);//如果NodePool中的Prefab不足,则新建一个
        }
        node.parent = scene;//设置父节点
        node.setPosition(this.node.width/2,this.node.height/4);//设置位置
    },
    despawnNMagnetPlayer (NMagnet) {    //销毁一个Prefab
        this.NMagnetPlayerPool.put(NMagnet);
    },

猜你喜欢

转载自blog.csdn.net/qq_33198758/article/details/82190921