飞机大战知识点总结
上一节03已经实现了单发逻辑,在上节基础上,实现双发功能,实现的效果图如下

1.制作双发的子弹预制体,复制粘贴Prefabs文件内的Bullet1,修改为Bullet2

2.定义双发子弹的世界坐标位置。参考上一节的需要注意:在文件Player内创建空节点,名称修改为bulletPost1,用来定位子弹发射的位置。
相同方式,创建空节点bulletPost2和bulletPost3,并手动拖动到指定位置。


继续实现Player.ts的双发逻辑,完整代码如下:
import { _decorator, Component, EventTouch, Input, input, instantiate, Node, Prefab, Vec3 } from 'cc';
const { ccclass, property } = _decorator;@ccclass('Player')
export class Player extends Component {// 子弹发射类型,1单发,2双发sendType:number = 2;/*** 单发,发射逻辑,先定义以下字段* sendRate:number 子弹发射频率* sendTime:number 子弹发射时间* bulletParent:Node 用来存放所有生成的子弹* bulletPost1:Node 第一种子弹的世界坐标位置* bulletPrefab1:Prefab 第一种子弹的预制体* * 逻辑分析:* 判断发射时间,sendTime+=dt >= sendRate 就需要发射子弹了,将sendTime重置为0* 通过instantiate(bulletPrefab1)拿掉子弹1的预制体,赋值给bullet1* 生成的所有子弹都要放在文件bulletParent内,所有通过addChild()方法,将bullet1 添加进去* 最后设置bullet1的世界坐标位置为:bulletPost1的worldPosition*/@propertysendRate:number = 0.5;sendTime:number = 0;@property(Node)bulletParent:Node = null;@property(Node)bulletPost1:Node = null;@property(Prefab)bulletPrefab1:Prefab = null;/*** 双发,发射逻辑* bulletPost2:Node 第二种子弹,左侧世界坐标位置* bulletPost3:Node 第二种子弹,右侧世界坐标位置* bulletPrefab2:Prefab 第二种子弹的预制体* */@property(Node)bulletPost2:Node = null;@property(Node)bulletPost3:Node = null;@property(Prefab)bulletPrefab2:Prefab = null;protected update(dt: number): void {if(this.sendType == 1){// 单发逻辑this.sendTime += dt;if(this.sendTime>= this.sendRate){this.sendTime = 0;const bullet1 = instantiate(this.bulletPrefab1)this.bulletParent.addChild(bullet1)bullet1.setWorldPosition(this.bulletPost1.worldPosition)}}else{// 双发逻辑this.sendTime += dt;if(this.sendTime>= this.sendRate){this.sendTime = 0;// 左侧子弹const bullet2 = instantiate(this.bulletPrefab2)this.bulletParent.addChild(bullet2)bullet2.setWorldPosition(this.bulletPost2.worldPosition)// 右侧子弹const bullet3 = instantiate(this.bulletPrefab2)this.bulletParent.addChild(bullet3)bullet3.setWorldPosition(this.bulletPost3.worldPosition)}}}// 以下内容为飞机的触摸移动方法protected onLoad(): void {// 1. 注册触摸事件input.on(Input.EventType.TOUCH_MOVE,this.onTouchMove,this);}protected onDestroy(): void {// 2.注销触摸事件input.off(Input.EventType.TOUCH_MOVE,this.onTouchMove,this);}// 触摸方法onTouchMove(event:EventTouch){// this.node.position:获取自身Player的位置// event中 getDeltaX(),getDeltaY():用来获取移动过程中的位置偏移// 通过这个偏移,来控制Player的位置偏移// this.node.setPosition:设置x,y,z轴的位置 const p = this.node.position;// 要移动的:目标坐标let targetPos = new Vec3(p.x+event.getDeltaX(),p.y+event.getDeltaY(),p.z);if(targetPos.x < -230){targetPos.x = -230}if(targetPos.x > 230){targetPos.x = 230}if(targetPos.y < -380){targetPos.y = -380}if(targetPos.y > 380){targetPos.y = 380}this.node.setPosition(targetPos)}
}
回到COCOS中,把对应的文件拖进去,运行完成双发逻辑效果。

最后在这里完善以下子弹的销毁功能
在子弹发射的Bullet.ts文件内,销毁
update(deltaTime: number) {const pos = this.node.position;this.node.setPosition(pos.x,pos.y+this.speed*deltaTime,pos.z)// 飞行距离超出屏幕外了,就销毁掉。if(pos.y>500){this.node.destroy()}
}
