Enemy.ts 19 KB

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