开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第13天,点击查看活动详情
上一次说到了子弹在场景中的显示,今天说下子弹的移动,在开始子弹移动前先完善其他两种子弹的
1.完善激光导弹,打开play.ts脚本
(1)增加发射激光导弹函数
//发射激光子弹
shootLightlBullet(){
let postBegin:Vec3=new Vec3() //定义子弹开始的位置
let normalBullet:Node=null;
//发射左边激光子弹
normalBullet= this.playerBulletFactory.createProduct(global.LIGHT_BULLET)//制作激光子弹
this.node.parent.addChild(normalBullet) //添加节点到画布
this.curPos=this.node.getPosition() //得到飞机当前位置
postBegin.x=this.curPos.x-50
postBegin.y=this.curPos.y+50 //设置到机头位置
normalBullet.setPosition(postBegin)
//发射右边激光子弹
normalBullet= this.playerBulletFactory.createProduct(global.LIGHT_BULLET)//制作激光子弹
this.node.parent.addChild(normalBullet) //添加节点到画布
this.curPos=this.node.getPosition() //得到飞机当前位置
postBegin.x=this.curPos.x+50
postBegin.y=this.curPos.y+50 //设置到机头位置
normalBullet.setPosition(postBegin)
}
(2)定义激光子弹定时器
lightBulletTimer:number=0; //激光子弹定时器
(3)定义是否发射激光子弹
isshootLight:boolean=false //是否发射激光子弹
(4)在update函数里调用发射激光子弹函数
//发射激光子弹
if(this.isshootLight){
this.lightBulletTimer += deltaTime
if(this.lightBulletTimer>1){
this.shootLightlBullet();
this.lightBulletTimer=0;
}
}
2. 完善导弹子弹
(1)增加发射导弹子弹函数
//发射导弹子弹
shootmissileBullet(){
let postBegin:Vec3=new Vec3() //定义子弹开始的位置
let normalBullet:Node=null;
normalBullet= this.playerBulletFactory.createProduct(global.MISSILE_BULLET)//制作导弹子弹
this.node.parent.addChild(normalBullet) //添加节点到画布
this.curPos=this.node.getPosition() //得到飞机当前位置
postBegin.x=this.curPos.x
postBegin.y=this.curPos.y+50 //设置到机头位置
normalBullet.setPosition(postBegin)
}
(2)定义导弹子弹定时器
missileBulletTimer:number=0; //导弹子弹定时器
(3)定义是否发射激光子弹
isshootMissile:boolean=false //是否发射导弹子弹
(4)在update函数里调用发射激光子弹函数
//发射导弹子弹
if(this.isshootMissile){
this.missileBulletTimer += deltaTime
if(this.missileBulletTimer>1.5){
this.shootmissileBullet();
this.missileBulletTimer=0;
}
}
3. 子弹移动。
(1)打开playerBullet脚本。定义子弹当前位置,子弹工厂和常驻节点
curPos:Vec3=null; //当前子弹位置
playerBulletFactory:gameFactory=null;
persistNode:Node=null;
(2)在Load 函数里拿到playerBulletFactory,注意()
onLoad(){
this.persistNode=find("PersistNode")
this.playerBulletFactory=this.persistNode.getComponent(persistNode).playerBulletFactory;
}
(3)注意,要引入find
(4)增加普通子弹移动行为函数
//普通子弹行为
normalBulletMove(deltaTime: number){
this.curPos=this.node.getPosition();
this.curPos.y +=500*deltaTime
this.node.setPosition(this.curPos)
if(this.curPos.y> 640 ){
this.playerBulletFactory.recycleProduct(this.node)
}
}
(5)增加激光子弹移动行为函数
//激光子弹行为
lightBulletMove(deltaTime: number){
this.curPos=this.node.getPosition();
this.curPos.y +=300*deltaTime
this.node.setPosition(this.curPos)
if(this.curPos.y> 640 ){
this.playerBulletFactory.recycleProduct(this.node)
}
}
4. 在update函数里调用子弹运行行为函数,这样子弹的移动功能就做好了
update(deltaTime: number) {
if(this.playerBulletType==global.NORMAL_BULLET){
this.normalBulletMove(deltaTime)
}else if(this.playerBulletType==global.LIGHT_BULLET){
this.lightBulletMove(deltaTime)
}
}
今天就到这里了,主要说了子弹的移动。可能写的过程中还有很多不好的地方,希望大家能指出来,在此,谢谢大家