CocosCreator之KUOKUO带你做疯狂炮台(1)

本次引擎2.0.5

编辑工具VSCode

本系列默认你不是特别小白,console.log(滑稽)

第一部分:子弹节点池,无限子弹。

新建工程;改成你喜欢布局;建个白色背景;保存成game场景。

然后我们建个炮台,,嗯,好看吧。

一个空节点(paotai),body炮身,shoot炮台;

(我们严谨一些,把空节点的大小改成100,125,然后调整一下位置,让炮管也包围进去)

好了,然后我们写个脚本来控制炮台;

paotai.js

cc.Class({
    extends: cc.Component,

    properties: {
        
    },

    onLoad () {
        // 拖动效果
        this.node.on(cc.Node.EventType.TOUCH_MOVE,function(event){
            var delta =event.getDelta();
            this.node.x +=delta.x;
        },this);
    },

    update (dt) {
        // 边界检测,这里的数值最好不要像我这么写,用引用
        // 主要展示思想
        if (this.node.x < -960 / 2 + 50 )
        {
            this.node.x = -960 / 2 + 50;
        }
        else if(this.node.x > 960 / 2 - 50)
        {
            this.node.x = 960 / 2 - 50;
        }
    },
});

好了,我们接下来做炮弹。

这就使用到了预制体,脚本里用节点池。

粉粉的子弹,记得绑上脚本。

子弹不可能只有1个,我们弄个子弹管理器(空节点)。

然后在脚本里弄节点池,并发射子弹:

bulletManager.js

cc.Class({
    extends: cc.Component,

    properties: {
        bullet:cc.Prefab,
        // 获取发射位置
        shoot:cc.Node,
    },

    onLoad () {
        this.bulletPool = new cc.NodePool();
        let initCount = 15;
        for (let i = 0; i < initCount; ++i) {
            let bullet = cc.instantiate(this.bullet); // 创建节点
            this.bulletPool.put(bullet); // 放入对象池
        }
    },

    createBullet () {
        let bullet = null;
        // 通过 size 接口判断对象池中是否有空闲的对象
        if (this.bulletPool.size() > 0) { 
            bullet = this.bulletPool.get();
        } 
        // 如果没有空闲对象,也就是对象池中备用对象不够时,我们就用 cc.instantiate 重新创建
        else {
            bullet = cc.instantiate(this.bulletPool);
        }
        // 将生成的敌人加入节点树
        bullet.parent = this.node; 
        //根据层级关系设定位置
        bullet.x = this.shoot.x + this.shoot.parent.x;
        bullet.y = this.shoot.y + this.shoot.parent.y;
        //bullet往上飞
        bullet.runAction(cc.moveBy(3,0,2000));
    },

    start () {
        this.schedule(this.createBullet,0.5,cc.macro.REPEAT_FOREVER,1);
    },

    // update (dt) {},
});

这样子弹会飞出去,并且随着手指移动,子弹也偏移。

接下来,我们让子弹回收。

bullet.js

cc.Class({
    extends: cc.Component,

    properties: {
        dt_time:0,
    },

    update (dt) {
        //回收不用每帧检测,这样写节约一点点性能
        this.dt_time += dt;
        if(this.dt_time >= 0.2){
            this.dt_time = 0;
            if(this.node.y > 1300){
                //回收前把动作都停了
                this.node.stopAllActions();
                //放入节点池
                this.node.parent.getComponent('bulletManager').bulletPool.put(this.node);
            }
        }
    },
});

怎么样,无限子弹就做好了。

我们下一部分做个小Boss敌人与hp显示。

O(∩_∩)O~~

猜你喜欢

转载自blog.csdn.net/kuokuo666/article/details/84144892