从0开始用CocosCreator开发飞机大战小游戏(八)

233 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第16天,点击查看活动详情

今天我们继续来完善这个碰撞的功能。

1. 打开playerBullet.ts脚本。

(1)定义enemyFactory工厂

    enemyFactory:gameFactory=null; //敌机工厂

(2)在onLoad函数里注册碰撞回调

        this.enemyFactory=this.persistNode.getComponent(persistNode).enemyFactory;

        let collider=this.node.getComponent(Collider2D)

        if(collider){

            collider.on(Contact2DType.BEGIN_CONTACT,this.onBeginContact,this)

        }

2. 完善碰撞后回调函数,这样碰撞功能就做完了   onBeginContact(selfCollider:Collider2D,otherCollider:Collider2D,contact:IPhysics2DContact | null){

        otherCollider.getComponent(enemy)

        this.enemyFactory.recycleProduct(otherCollider.node) //敌机消失

        this.playerBulletFactory.recycleProduct(this.node) //子弹消失

    }

3. 之前我们做了普通子弹和激光子弹的移动行为,还有导弹的移动行为还没有做,接下来完善它。打开脚本playerBullet.ts。

(1)定义导弹移动速度

    missileBulletMoveSpeed:number=150 //导弹移动速度

(2)增加导弹移动行为函数

    //导弹子弹行为

    missileBulletMove(deltaTime: number){

        let enemy:Node=this.node.parent.getChildByName("enemy") //获取敌机节点

        this.curPos=this.node.getPosition()  //获取子弹位置

        if(enemy !=null){

            let enemyPos:Vec3=enemy.getPosition() //获取敌机位置

            let normalizeVec:Vec3=enemyPos.subtract(this.curPos).normalize() //获取子弹指向敌机的单位向量

            this.curPos.x+=normalizeVec.x * this.missileBulletMoveSpeed * deltaTime //子弹沿着向量方向移动

            this.curPos.y+=normalizeVec.y * this.missileBulletMoveSpeed * deltaTime   //子弹沿着向量方向移动

            this.node.setPosition(this.curPos)

            this.node.angle=v2(0,1).signAngle(v2(normalizeVec.x,normalizeVec.y))*180/Math.PI; //设置导弹夹度

        }else{

            this.curPos.y +=500*deltaTime

            this.node.setPosition(this.curPos)

            this.node.angle=v2(0,1).signAngle(v2(0,1)) * 180/Math.PI //修正子弹的角度    

        }

        if(this.curPos.y> 640 ){

            this.playerBulletFactory.recycleProduct(this.node)

        }

    }

  (3)在init函数处增加修改子弹的角度

    this.node.angle=v2(0,1).signAngle(v2(0,1)) * 180/Math.PI //修正子弹的角度

(4)在update函数中增加对导弹行为的移动函数的调用。

    update(deltaTime: number) {

       if(this.playerBulletType==global.NORMAL_BULLET){

        this.normalBulletMove(deltaTime)

       }else if(this.playerBulletType==global.LIGHT_BULLET){

        this.lightBulletMove(deltaTime)

       }else if(this.playerBulletType==global.MISSILE_BULLET){

        this.missileBulletMove(deltaTime)

      }

    }

4. 接下来开始开发敌机发躲子弹功能。先做敌机子弹预制体

(1)在Canvas新建一个Sprite(精灵),并且命名为enemyBullet image.png

(2)关联敌机子弹图片资源 image.png

(3)在script文件夹下新建一个脚本,并且命名为enemyBullet image.png

(4)将脚本enemyBullet挂载到enemyBullet节点上 image.png

(5)将enemyBullet拖动到prefab文件夹里  image.png

(6)删除Canvas下的enemyBullet。这样敌机子弹的预制体就制作完了

5. 在script文件夹下新建一个脚本,并且命名为enemyBulletFactory image.png

今天就到这里了,主要说了碰撞功能,下一次再来说说怎样敌机发射子弹。可能写的过程中还有很多不好的地方,希望大家能指出来,在此,谢谢大家