Enemy.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. import { _decorator, Node, Tween, Vec3, ProgressBar, UIOpacity, tween, Label, SkeletalAnimation, Animation, SphereCollider, CylinderCollider, MeshCollider, Collider} from 'cc';
  2. import { Game } from './Game';
  3. import { Player } from './Player';
  4. import { Utils } from '../utils/Utils';
  5. import { ResUtil } from '../utils/ResUtil';
  6. import MsgHints from '../utils/MsgHints';
  7. import { userIns } from '../data/UserData';
  8. import { autoBind } from '../extend/AutoBind';
  9. import { BaseExp } from '../core/base/BaseExp';
  10. import { GunBase } from '../items/base/GunBase';
  11. import { PoolManager } from '../core/manager/PoolManager';
  12. import { audioMgr } from '../core/manager/AudioManager';
  13. import { Constants } from '../data/Constants';
  14. const { ccclass, property } = _decorator;
  15. //部位类型
  16. export enum EPartType {
  17. head = "headCollider", //头部的碰撞体
  18. body = "bodyCollider", //身体的碰撞体
  19. tank = "tankCollider", //坦克的碰撞体
  20. shield = "shieldCollider", //盾的碰撞体
  21. sundries = "sundriesCollider", //杂物的碰撞体
  22. }
  23. //敌人动作类型
  24. export enum EAnimType {
  25. idle = "idle", //idle 待机状态
  26. die = "die", //die 死亡状态
  27. shoot = "shoot", //shoot 射击状态
  28. walk = "walk", //shoot 行走状态
  29. }
  30. //敌人类型枚举
  31. export enum EnemyType {
  32. SoldierPistol = 10001, // 大兵 - 普通士兵,使用手枪
  33. SniperSoldier = 10002, // 狙击兵 - 远程攻击单位,使用狙击枪
  34. ShieldSoldier = 10003, // 盾牌兵 - 高生命值防御单位,使用手枪和盾牌
  35. SnipeCaptain = 20001, // 狙击队长 - BOSS单位,使用强力狙击枪
  36. ScatterCaptain = 20002, // 机枪队长 - BOSS单位,使用高射速机关枪
  37. Tank = 20003, // 坦克 - BOSS单位,高生命值重型单位
  38. GeneralPistol = 20004 // 将军 - BOSS单位,综合型强力敌人
  39. }
  40. //武器类型枚举
  41. export enum WeaponType {
  42. Pistol = 1001, // 大兵手枪 将军手枪
  43. Sniper = 1002, // 狙击兵狙击枪 狙击队长狙击枪
  44. Shield = 1003, // 盾牌兵盾牌
  45. Scatter = 1005, // 机枪队长机关枪
  46. Tank_Pao = 1006, // 坦克
  47. }
  48. @ccclass('Enemy')
  49. export class Enemy extends BaseExp {
  50. @autoBind({type: ProgressBar,tooltip: "敌人血量"})
  51. public hpBar: ProgressBar = null!;
  52. @autoBind({type: Node,tooltip: "敌人受伤节点"})
  53. public hurt_num: Node = null!;
  54. @autoBind({type: Collider,tooltip: "敌人头部"})
  55. public headCollider: Collider = null!;
  56. @autoBind({type: Collider,tooltip: "敌人身体"})
  57. public bodyCollider: Collider = null!;
  58. @autoBind({type: Collider,tooltip: "坦克身体"})
  59. public tankCollider: Collider = null!;
  60. @autoBind({type: Node,tooltip: "坦克行走"})
  61. public tank_walk: Node = null!;
  62. @autoBind({type: Node,tooltip: "坦克射击"})
  63. public tank_shoot: Node = null!;
  64. //敌人动画节点
  65. private skeletalAnim: SkeletalAnimation = null!;
  66. //根据敌人类型动态获取
  67. public enemyNode: Node = null!;
  68. public oTween: Tween<object>;//敌人透明变化
  69. public defaultSpeed: number = 0;
  70. public speed: number = 0;
  71. public isDead: boolean = false;
  72. //拥有的枪
  73. public gun: GunBase = null;
  74. //盾的节点
  75. public shieldNode: Node = null!;
  76. //拥有的盾可以使用的血量
  77. private _shieldHp: number = 0;
  78. public set shieldHp(value: number) {
  79. this._shieldHp = value;
  80. if(this._shieldHp <= 0){
  81. this.removeShield();
  82. }
  83. }
  84. public get shieldHp(): number {
  85. return this._shieldHp;
  86. }
  87. //当前金币的值
  88. public goldCount : number = 0;
  89. //玩家
  90. public player: Player = null!;
  91. //运动方向
  92. public moveDir: Vec3 = new Vec3();
  93. //设置的血量
  94. public curHP: number = 0;
  95. //敌人的原始血量
  96. public originHP: number = 0;
  97. //是否是没打死逃逸
  98. public escape: boolean = false;
  99. //敌人数据
  100. public data: any = null;
  101. //是否能锁定攻击对象了
  102. public isCanLock: boolean = false;
  103. //是否是在开火
  104. private isFire: boolean = false;
  105. //敌人行走的路径
  106. public pathList: Array<Vec3> = [];
  107. //当前行走的位置
  108. public curMoveIndex: number = 0;
  109. //枪旋转角度
  110. public angle: number = 0;
  111. //新增警戒状态属性
  112. public isAlert: boolean = false;
  113. start() {
  114. this.hurt_num.active = false;
  115. }
  116. /**
  117. * 初始化数据
  118. */
  119. public async init(data: any){
  120. this.data = data;
  121. this.player = Game.I.player.getComponent(Player);
  122. const isTank:boolean = this.isTank();
  123. this.enemyNode = this.node.getChildByName(data.prb_name);
  124. if(isTank){
  125. this.tankCollider["args"] = [EPartType.tank,this];
  126. }else{
  127. this.headCollider["args"] = [EPartType.head,this];
  128. this.bodyCollider["args"] = [EPartType.body,this];
  129. this.skeletalAnim = this.enemyNode.getComponent(SkeletalAnimation);
  130. if(this.skeletalAnim){
  131. this.skeletalAnim?.play(EAnimType.idle);
  132. }
  133. }
  134. if(!this.enemyNode){
  135. MsgHints.show(`不存在:${JSON.stringify(data)}`)
  136. return;
  137. }
  138. this.isAlert = false;
  139. this.data = this.enemyData(data);
  140. this.isDead = false;
  141. this.escape = false;
  142. //设置血量
  143. this.curHP = this.originHP = data.hp;
  144. //敌人速度
  145. const s: number = data.speed * 3;
  146. this.speed = s;
  147. this.defaultSpeed = s;
  148. //设置枪的数据
  149. await this.createGun();
  150. //恢复初始雪条
  151. this.hpBar.progress = 1;
  152. this.hpBar.node.active = false;
  153. this.endFire();
  154. }
  155. /**
  156. * 把武器的参数带到敌人身上
  157. */
  158. public enemyData(data:any){
  159. if(!data)return;
  160. //主武器id
  161. const mainWeaponID:number = data.weapon_id_1;
  162. let hp: number = Utils.clone(data).hp;
  163. let gData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == mainWeaponID);
  164. //副武器 盾上的血量
  165. const secondWeaponID:number = data.weapon_id_2;
  166. if(secondWeaponID != 0){
  167. let sData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == secondWeaponID);
  168. if(sData && sData.hp > 0){
  169. data.hp += hp + sData.shield_hp;
  170. }
  171. }
  172. return Object.assign(data,gData);
  173. }
  174. /**
  175. * 创建英雄所拥有的枪
  176. */
  177. public async createGun(){
  178. this.removeGun();
  179. //敌人主武器
  180. let gunPos:Node = this.enemyNode.getChildByName("gun_pos");
  181. const mainWeaponID:number = this.data.weapon_id_1;
  182. let mData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == mainWeaponID);
  183. let gunNode:Node = await ResUtil.loadRes(`enemy/gun/${mData.gun_prb_name}`,this.enemyNode) as Node;
  184. this.gun = gunNode.getComponent(GunBase);
  185. gunNode.active = true;
  186. gunNode.parent = gunPos.parent;
  187. gunNode.worldPosition = gunPos.worldPosition.clone();
  188. gunNode.eulerAngles = gunPos.eulerAngles.clone();
  189. this.gun.init(this.data,this);
  190. //敌人附武器
  191. const secondWeaponID:number = this.data.weapon_id_2;
  192. if(secondWeaponID != 0){
  193. let sData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == secondWeaponID);
  194. let shieldNode:Node = await ResUtil.loadRes(`enemy/gun/${sData.gun_prb_name}`,this.enemyNode) as Node;
  195. let shieldPos:Node = this.enemyNode.getChildByName("shield_pos");
  196. shieldNode.active = true;
  197. shieldNode.parent = shieldPos.parent;
  198. shieldNode.worldPosition = shieldPos.worldPosition.clone();
  199. shieldNode.eulerAngles = shieldPos.eulerAngles.clone();
  200. shieldNode.children[0].getComponent(Collider)["args"] = [EPartType.shield,this];
  201. this.shieldNode = shieldNode;
  202. this.shieldHp = sData.shield_hp;
  203. }
  204. }
  205. /**
  206. * 移除枪回收武器的时候调用
  207. */
  208. public removeGun(){
  209. if(this.gun){
  210. this.gun.endFire();
  211. PoolManager.putNode(this.gun.node);
  212. this.gun = null;
  213. }
  214. this.isFire = false;
  215. this.removeShield();
  216. }
  217. /**
  218. * 移除盾
  219. */
  220. public removeShield(){
  221. if(this.shieldNode){
  222. PoolManager.putNode(this.shieldNode);
  223. this.shieldNode = null;
  224. }
  225. this._shieldHp = 0;
  226. }
  227. /**
  228. * 扣掉血
  229. * @param hp 血
  230. * @param pData 英雄数据
  231. * @param isHeadShot 是否是爆头
  232. */
  233. public subHP(hp: number, pData:any,isHeadShot: boolean = false){
  234. if(Game.I.isPause
  235. ||this.isDead
  236. ||hp == null
  237. ||this.curHP <= 0){
  238. return;
  239. }
  240. this.hpBar.node.active = true;
  241. this.scheduleOnce(() => {
  242. if(this.hpBar){this.hpBar.node.active = false;}
  243. }, 0.8);
  244. this.curHP -= hp;
  245. //这种是伤害超级高直接死亡了
  246. if(hp > this.originHP){
  247. this.escape = false;
  248. this.showHurt(Utils.numberToString(hp));
  249. this.recycle()
  250. return;
  251. }
  252. //敌人死亡
  253. if(this.curHP <= 0 && !this.isDead){
  254. //爆头击杀播放音效
  255. if(isHeadShot){
  256. audioMgr.playOneShot(Constants.audios.head_shot);
  257. }
  258. this.escape = false;
  259. this.recycle();
  260. }else{//进度条和单独扣血
  261. this.hpBar.progress = this.curHP / this.originHP;
  262. this.showHurt(Utils.numberToString(hp));
  263. }
  264. }
  265. /**
  266. * 开始敌人移动,面向玩家行走
  267. */
  268. public walk(points:Vec3[]) {
  269. if(points.length <= 0)return;
  270. this.curMoveIndex = 0;
  271. this.pathList = points;
  272. const time: number = 1 / this.data.speed;
  273. if(this.isTank()){
  274. this.tank_walk.active = true;
  275. this.tank_shoot.active = false;
  276. }else{
  277. ResUtil.playSkeletalAnim(this.skeletalAnim,EAnimType.walk,time);
  278. }
  279. this.updateDir(points[0].clone());
  280. }
  281. /**
  282. * 开始攻击
  283. */
  284. public beginFire(){
  285. if(this.player
  286. && !this.player.isDead
  287. && this.gun){
  288. this.isFire = true;
  289. this.gun.fire();
  290. }
  291. }
  292. /**
  293. * 结束攻击
  294. */
  295. public endFire(){
  296. this.gun.endFire();
  297. this.isFire = false;
  298. }
  299. /**
  300. * 回收敌人节点
  301. * @param f 是否是游戏进行中的正常回收 程序主动回收不参数个数统计和加分这些
  302. * @returns
  303. */
  304. public recycle(f: boolean = true){
  305. if(!this.node
  306. ||this.isDead){
  307. return;
  308. };
  309. this.removeGun();
  310. this.curHP = 0;
  311. if(!this.isTank()){
  312. this.skeletalAnim.play(EAnimType.die);
  313. }
  314. this.isDead = true;
  315. this.hpBar.node.active = false;
  316. let death: Function = function(inite: boolean){
  317. this.node.getComponent(UIOpacity).opacity = 255;
  318. PoolManager.putNode(this.node);
  319. if(inite){
  320. Game.I.buildEnemys.subtractEnemy(this);
  321. }
  322. }.bind(this,f);
  323. if(this.oTween){this.oTween?.stop()};
  324. if(f){//修改透明度
  325. let op: UIOpacity = this.node.getComponent(UIOpacity);
  326. this.oTween = tween(op)
  327. .to(0.15,{ opacity: 0})
  328. .call(()=>{death();})
  329. .start();
  330. }else{
  331. death();
  332. }
  333. }
  334. /**
  335. * 展示敌人受到的伤害
  336. * @param hpStr
  337. */
  338. public showHurt(hpStr: string) {
  339. if(Game.I.isGameOver || this.isDead) return;
  340. //创建3D伤害数字
  341. const n = PoolManager.getNode(this.hurt_num, this.hurt_num.parent);
  342. n.getComponent(Label).string = hpStr;
  343. const oPos: Vec3 = this.hpBar.node.position.clone();
  344. n.position = oPos;
  345. const oScale: Vec3 = this.hurt_num.scale.clone();
  346. n.scale = oScale;
  347. n.getComponent(UIOpacity).opacity = 255;
  348. let bezier: Vec3[] = [];
  349. let num: number = 100;
  350. let forward = Utils.getRandomFloat(0, 1) > 0.5 ;
  351. if (forward) {
  352. bezier = [new Vec3(-(10/num)+oPos.x, (30/num)+oPos.y), new Vec3((-40/num)+oPos.x, (40/num)+oPos.y), new Vec3((-60/num)+oPos.x, oPos.y)];
  353. } else {
  354. bezier = [new Vec3((10/num)+oPos.x, (30/num)+oPos.y), new Vec3((40/num)+oPos.x, (40/num)+oPos.y), new Vec3((60/num)+oPos.x, oPos.y)];
  355. }
  356. n.position = new Vec3(bezier[2].x,bezier[2].y - (80/num),oPos.z);
  357. //贝塞尔曲线坐标函数
  358. let twoBezier = (t: number, p1: Vec3, cp: Vec3, p2: Vec3) => {
  359. let x = (1 - t) * (1 - t) * p1.x + 2 * t * (1 - t) * cp.x + t * t * p2.x;
  360. let y = (1 - t) * (1 - t) * p1.y + 2 * t * (1 - t) * cp.y + t * t * p2.y;
  361. return new Vec3(x, y, oPos.z);
  362. };
  363. let time: number = 0.65;
  364. tween(n)
  365. .parallel(
  366. tween()
  367. .to(time,{ scale: new Vec3(oScale.x * 0.4,oScale.y * 0.4,oScale.z * 0.4)}),
  368. tween()
  369. .to(time, bezier[2], {
  370. onUpdate: (target: Vec3, ratio: number) => {
  371. if(n.parent){
  372. const pos: Vec3 = twoBezier(ratio, bezier[0], bezier[1], bezier[2]);
  373. n.position = new Vec3(pos.x,pos.y - (80/num),oPos.z)
  374. }
  375. }
  376. })
  377. ).call(function(){
  378. tween(this.getComponent(UIOpacity))
  379. .to(0.15,{opacity: 0})
  380. .call(()=>{
  381. PoolManager.putNode(this);
  382. })
  383. .start();
  384. }.bind(n)).start();
  385. }
  386. /**
  387. * 计算是否命中玩家
  388. * @returns 返回命中状态
  389. */
  390. public calculateIsHit():boolean{
  391. let isGuaranteedHit: boolean = false;
  392. //获取射击的精准度
  393. const data:any = this.getDifficultyData();
  394. //生成0-1随机数用于命中判定 根据precision范围确定命中逻辑
  395. const random = Math.random();
  396. if(data.precision < 0){//负值100%不命中
  397. isGuaranteedHit = false;
  398. }else if(data.precision > 1) {//超过1 100%命中
  399. isGuaranteedHit = true;
  400. }else {//正常范围:随机判定
  401. isGuaranteedHit = random <= data.precision;
  402. }
  403. return isGuaranteedHit;
  404. }
  405. /**
  406. * 轻松杀敌增加游戏难度 只有单其他附加因素 例如:连杀等叠加状态 给敌人增加血
  407. */
  408. public addDiffHP(){
  409. if(!this.node
  410. ||this.isDead
  411. ||Game.I.isGameOver
  412. ||this.isDead){
  413. return;
  414. };
  415. const data:any = this.getDifficultyData();
  416. if(data.hp_ratio > 0){
  417. this.curHP += this.originHP * data.hp_ratio;
  418. }
  419. }
  420. /**
  421. * 敌人的射击的精准度 获得难度数据
  422. */
  423. public getDifficultyData(): any{
  424. //获取基础精准度(玩家预设值)
  425. const precision: number = userIns.getCurLevelData().precision;
  426. let basePrecision: number = precision;
  427. let diff:any = {
  428. precision: precision,//增加或减少的精准度 0-100%
  429. hp_ratio: 0,//增加或减少的血量 0-100%
  430. reaction_time: 0,//增加或减少的反应时间 0-100%
  431. }
  432. const each: number = Math.floor(Game.I.buildEnemys.getCurKillNum() / 3);
  433. //连杀3个敌人的次数 AI精准度增加1%
  434. diff.precision += each * 0.01;
  435. //连续通关3次以上才有的难度
  436. const lx_num: number = 3;
  437. if(userIns.passNum > lx_num){//1、连续通关 AI生命值增加15% 精准度增加5%
  438. diff.precision += userIns.passNum * 0.05;
  439. diff.precision = Math.min(basePrecision, 0.9);
  440. diff.hp_ratio += userIns.passNum * 0.15;
  441. diff.hp_ratio = Math.min(diff.hp_ratio, 1);
  442. }else{//2、通关失败 下一局 AI精准度下降5% AI反应时间增加0.5s
  443. diff.precision -= userIns.passNum * 0.05;
  444. diff.precision = Math.max(diff.precision, 0.1);
  445. diff.reaction_time += 0.5;
  446. }
  447. return diff;
  448. }
  449. /**
  450. * 更新敌人行走和变化方向
  451. */
  452. protected update(dt: number): void {
  453. if(Game.I.isGameOver
  454. || Game.I.isPause
  455. || !this.data
  456. || this.isDead) return;
  457. const targetPos = this.pathList[this.curMoveIndex];
  458. if(!targetPos)return;
  459. //保持速度调节逻辑
  460. dt = dt / Game.I.map.multiplySpeed();
  461. const currentPos = this.node.worldPosition.clone();
  462. const toTarget = targetPos.clone().subtract(currentPos);
  463. //敌人移动
  464. const moveDir = new Vec3();
  465. Vec3.subtract(moveDir, targetPos, currentPos);
  466. let distance:number = moveDir.length();
  467. //计算实际应移动距离
  468. const moveDistance = this.speed * dt;
  469. if(moveDistance > 0) {
  470. //使用标准化方向向量 + 实际移动距离
  471. const newPos = currentPos.add(toTarget.normalize().multiplyScalar(moveDistance));
  472. //添加移动平滑过渡 平滑系数 10-15比较好 值越大越平滑
  473. const smoothFactor = 20;
  474. this.node.worldPosition = Vec3.lerp(
  475. new Vec3(),
  476. currentPos,
  477. newPos,
  478. Math.min(1, dt * smoothFactor)
  479. );
  480. //更新方向
  481. const isLastPathPoint = this.curMoveIndex == this.pathList.length - 1;
  482. const dirTarget = isLastPathPoint
  483. ? Game.I.player.node.worldPosition
  484. : this.pathList[this.curMoveIndex + 1];
  485. this.updateDir(dirTarget);
  486. }
  487. //到达判断增加缓冲范围
  488. if(moveDistance > distance) {
  489. //从出生点走到第二个点就是外门第一个点就开门 并且门没有被打开
  490. if(this.curMoveIndex == 1
  491. && !Game.I.buildEnemys.isOpenDoor){
  492. Game.I.map.openDoor();
  493. Game.I.buildEnemys.isOpenDoor = true;
  494. }
  495. this.curMoveIndex++;
  496. if (this.curMoveIndex >= this.pathList.length) {
  497. this.beginFire();
  498. if(this.isTank()){
  499. this.tank_walk.active = false;
  500. this.tank_shoot.active = true;
  501. } else {
  502. const time: number = 1 / this.data.atk_speed;
  503. ResUtil.playSkeletalAnim(this.skeletalAnim, EAnimType.shoot, time);
  504. }
  505. this.updateDir(Game.I.player.node.worldPosition);
  506. }
  507. }
  508. }
  509. /**
  510. * 更新敌人方向(根据目标坐标转向)
  511. * @param targetPos 目标坐标(路径点或玩家坐标)
  512. */
  513. public updateDir(targetPos: Vec3){
  514. const curPos = this.node.worldPosition.clone();
  515. //从目标位置指向当前位置
  516. const targetDir = Vec3.subtract(new Vec3(), curPos, targetPos);
  517. targetDir.normalize();
  518. //平滑插值转向 避免瞬间转向
  519. const currentDir = this.node.forward.clone();
  520. Vec3.slerp(currentDir, currentDir, targetDir, 0.15);
  521. this.node.forward = currentDir;
  522. }
  523. /**
  524. * 是否是坦克
  525. */
  526. public isTank():boolean{
  527. return this.data.id == EnemyType.Tank;
  528. }
  529. }