Enemy.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. import { _decorator, Node, Tween, Vec3, ProgressBar, UIOpacity, tween, Label, SkeletalAnimation, TiledUserNodeData, SphereCollider, CylinderCollider, MeshCollider} 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= "shieldBearer", //盾的碰撞体
  21. }
  22. //敌人动作类型
  23. export enum EAnimType {
  24. idle = "idle", //idle 待机状态
  25. die = "die", //die 死亡状态
  26. shoot = "shoot", //shoot 射击状态
  27. walk = "walk", //shoot 行走状态
  28. }
  29. //敌人类型枚举
  30. export enum EnemyType {
  31. SoldierPistol = 10001, // 大兵 - 普通士兵,使用手枪
  32. SniperSoldier = 10002, // 狙击兵 - 远程攻击单位,使用狙击枪
  33. ShieldSoldier = 10003, // 盾牌兵 - 高生命值防御单位,使用手枪和盾牌
  34. SnipeCaptain = 20001, // 狙击队长 - BOSS单位,使用强力狙击枪
  35. ScatterCaptain = 20002, // 机枪队长 - BOSS单位,使用高射速机关枪
  36. Tank = 20003, // 坦克 - BOSS单位,高生命值重型单位
  37. GeneralPistol = 20004 // 将军 - BOSS单位,综合型强力敌人
  38. }
  39. //武器类型枚举
  40. export enum WeaponType {
  41. Pistol = 1001, // 大兵手枪 将军手枪
  42. Sniper = 1002, // 狙击兵狙击枪 狙击队长狙击枪
  43. Shield = 1003, // 盾牌兵盾牌
  44. Scatter = 1005, // 机枪队长机关枪
  45. Tank_Pao = 1006, // 坦克
  46. }
  47. @ccclass('Enemy')
  48. export class Enemy extends BaseExp {
  49. @autoBind({type: ProgressBar,tooltip: "敌人血量"})
  50. public hpBar: ProgressBar = null!;
  51. @autoBind({type: Node,tooltip: "敌人受伤节点"})
  52. public hurt_num: Node = null!;
  53. @autoBind({type: SphereCollider,tooltip: "敌人头部"})
  54. public headCollider: SphereCollider = null!;
  55. @autoBind({type: CylinderCollider,tooltip: "敌人身体"})
  56. public bodyCollider: CylinderCollider = null!;
  57. @autoBind({type: MeshCollider,tooltip: "坦克身体"})
  58. public tankCollider: MeshCollider = null!;
  59. //人物动画节点
  60. private skeletalAnim: SkeletalAnimation = null!;
  61. //根据敌人类型动态获取
  62. public enemyNode: Node = null!;
  63. public oTween: Tween<object>;//敌人透明变化
  64. public defaultSpeed: number = 0;
  65. public speed: number = 0;
  66. public isDead: boolean = false;
  67. //拥有的枪
  68. public gun: GunBase = null;
  69. //盾的节点
  70. public shieldNode: Node = null!;
  71. //拥有的盾可以使用的血量
  72. private _shieldHp: number = 0;
  73. public set shieldHp(value: number) {
  74. this._shieldHp = value;
  75. if(this._shieldHp <= 0){
  76. this.removeShield();
  77. }
  78. }
  79. public get shieldHp(): number {
  80. return this._shieldHp;
  81. }
  82. //当前金币的值
  83. public goldCount : number = 0;
  84. //玩家
  85. public player: Player = null!;
  86. //运动方向
  87. public moveDir: Vec3 = new Vec3();
  88. //设置的血量
  89. public totalHP: number = 0;
  90. //是否是没打死逃逸
  91. public escape: boolean = false;
  92. //敌人数据
  93. public data: any = null;
  94. //是否能锁定攻击对象了
  95. public isCanLock: boolean = false;
  96. //是否是在开火
  97. private isFire: boolean = false;
  98. //敌人行走的路径
  99. public pathList: Array<Vec3> = [];
  100. //当前行走的位置
  101. public curMoveIndex: number = 0;
  102. //枪旋转角度
  103. public angle: number = 0;
  104. //新增警戒状态属性
  105. public isAlert: boolean = false;
  106. start() {
  107. this.hurt_num.active = false;
  108. }
  109. /**
  110. * 初始化数据
  111. */
  112. public async init(data: any){
  113. this.data = data;
  114. const eNameTypes:string[] = Object.keys(EnemyType)
  115. .filter(key => isNaN(Number(key)))
  116. .map(key => key.charAt(0).toLowerCase() + key.slice(1));
  117. let eNodes:Node[] = this.node.children
  118. .filter(e => eNameTypes.includes(e.name));
  119. const ids: number[] = Object.values(EnemyType).filter(v => typeof v === 'number') as number[];
  120. ids.forEach((e_id:number,i:number) => {
  121. let active : boolean = e_id == data.id;
  122. let eTypeNode:Node = eNodes[i];
  123. eTypeNode.active = active;
  124. if(active){
  125. this.enemyNode = eTypeNode;
  126. this.skeletalAnim = eTypeNode.getComponent(SkeletalAnimation);
  127. }
  128. });
  129. if(!this.enemyNode){
  130. MsgHints.show(`不存在:${JSON.stringify(data)}`)
  131. return;
  132. }
  133. if(this.isTank()){
  134. this.skeletalAnim?.play(EAnimType.walk);
  135. this.headCollider.enabled = false;
  136. this.bodyCollider.enabled = false;
  137. this.tankCollider.enabled = true;
  138. }else{
  139. this.skeletalAnim?.play(EAnimType.idle);
  140. this.headCollider.enabled = true;
  141. this.bodyCollider.enabled = true;
  142. this.tankCollider.enabled = false;
  143. }
  144. this.player = Game.I.player.getComponent(Player);
  145. this.isAlert = false;
  146. this.data = this.enemyData(data);
  147. this.isDead = false;
  148. this.escape = false;
  149. //设置血量
  150. this.totalHP = data.hp;
  151. //敌人速度
  152. const s: number = data.speed * 3;
  153. this.speed = s;
  154. this.defaultSpeed = s;
  155. //设置枪的数据
  156. await this.createGun();
  157. //恢复初始雪条
  158. this.hpBar.progress = 1;
  159. this.hpBar.node.active = false;
  160. this.endFire();
  161. }
  162. /**
  163. * 把武器的参数带到敌人身上
  164. */
  165. public enemyData(data:any){
  166. if(!data)return;
  167. //主武器id
  168. const mainWeaponID:number = data.weapon_id_1;
  169. let hp: number = Utils.clone(data).hp;
  170. let gData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == mainWeaponID);
  171. //副武器 盾上的血量
  172. const secondWeaponID:number = data.weapon_id_2;
  173. if(secondWeaponID != 0){
  174. let sData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == secondWeaponID);
  175. if(sData && sData.hp > 0){
  176. data.hp += hp + sData.shield_hp;
  177. }
  178. }
  179. return Object.assign(data,gData);
  180. }
  181. /**
  182. * 创建英雄所拥有的枪
  183. */
  184. public async createGun(){
  185. this.removeGun();
  186. //敌人主武器
  187. let gunPos:Node = this.enemyNode.getChildByName("gun_pos");
  188. const mainWeaponID:number = this.data.weapon_id_1;
  189. let mData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == mainWeaponID);
  190. let gunNode:Node = await ResUtil.loadGunRes(`enemy/${mData.gun_prb_name}`,this.enemyNode) as Node;
  191. this.gun = gunNode.getComponent(GunBase);
  192. gunNode.active = true;
  193. gunNode.parent = gunPos.parent;
  194. gunNode.worldPosition = gunPos.worldPosition.clone();
  195. gunNode.eulerAngles = gunPos.eulerAngles.clone();
  196. this.gun.init(this.data,this);
  197. //敌人附武器
  198. const secondWeaponID:number = this.data.weapon_id_2;
  199. if(secondWeaponID != 0){
  200. let sData:any = userIns.enemyWeaponTable.find(e=>e.gun_id == secondWeaponID);
  201. let shieldNode:Node = await ResUtil.loadGunRes(`enemy/${sData.gun_prb_name}`,this.enemyNode) as Node;
  202. let shieldPos:Node = this.enemyNode.getChildByName("shield_pos");
  203. shieldNode.active = true;
  204. shieldNode.parent = shieldPos.parent;
  205. shieldNode.worldPosition = shieldPos.worldPosition.clone();
  206. shieldNode.eulerAngles = shieldPos.eulerAngles.clone();
  207. this.shieldNode = shieldNode;
  208. this.shieldHp = sData.shield_hp;
  209. }
  210. }
  211. /**
  212. * 移除枪回收武器的时候调用
  213. */
  214. public removeGun(){
  215. if(this.gun){
  216. this.gun.endFire();
  217. PoolManager.putNode(this.gun.node);
  218. this.gun = null;
  219. }
  220. this.isFire = false;
  221. this.removeShield();
  222. }
  223. /**
  224. * 移除盾
  225. */
  226. public removeShield(){
  227. if(this.shieldNode){
  228. PoolManager.putNode(this.shieldNode);
  229. this.shieldNode = null;
  230. }
  231. this._shieldHp = 0;
  232. }
  233. /**
  234. * 扣掉血
  235. * @param hp 血
  236. * @param pData 英雄数据
  237. * @param isHeadShot 是否是爆头
  238. */
  239. public subHP(hp: number, pData:any,isHeadShot: boolean = false){
  240. if(Game.I.isPause
  241. ||this.isDead
  242. ||hp == null
  243. ||this.totalHP <= 0){
  244. return;
  245. }
  246. this.hpBar.node.active = true;
  247. this.scheduleOnce(() => {
  248. if(this.hpBar){this.hpBar.node.active = false;}
  249. }, 0.8);
  250. this.totalHP -= hp;
  251. //这种是伤害超级高直接死亡了
  252. if(hp > this.totalHP){
  253. this.escape = false;
  254. this.showHurt(Utils.numberToString(hp));
  255. this.recycle()
  256. return;
  257. }
  258. //敌人死亡
  259. if(this.totalHP <= 0 && !this.isDead){
  260. //爆头击杀播放音效
  261. if(isHeadShot){
  262. audioMgr.playOneShot(Constants.audios.head_shot);
  263. }
  264. this.escape = false;
  265. this.recycle();
  266. }else{//进度条和单独扣血
  267. this.hpBar.progress = this.totalHP / this.data.hp;
  268. this.showHurt(Utils.numberToString(hp));
  269. }
  270. }
  271. /**
  272. * 开始敌人移动,面向玩家行走
  273. */
  274. public walk(points:Vec3[]) {
  275. if(points.length <= 0)return;
  276. this.curMoveIndex = 0;
  277. this.pathList = points;
  278. this.skeletalAnim.play(EAnimType.walk);
  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.totalHP = 0;
  311. this.skeletalAnim.play(EAnimType.die);
  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 true;// 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. if (this.curMoveIndex >= this.pathList.length) {
  457. return;
  458. }
  459. dt = dt / Game.I.map.multiplySpeed();
  460. const targetPos = this.pathList[this.curMoveIndex];
  461. const currentPos = this.node.worldPosition.clone();
  462. //计算移动方向和剩余距离
  463. const moveDirection = new Vec3();
  464. Vec3.subtract(moveDirection, targetPos, currentPos);
  465. const distanceToTarget = moveDirection.length();
  466. //计算本帧移动量
  467. const moveDistance = this.speed * dt;
  468. const normalizedDir = moveDirection.normalize();
  469. if (distanceToTarget > 0.1) {//添加小阈值防止抖动 线性插值平滑移动
  470. const newPos = currentPos.add(normalizedDir.multiplyScalar(moveDistance));
  471. this.node.worldPosition = newPos;
  472. //更新面向方向(仅在需要时更新)
  473. if(moveDirection.lengthSqr() > 0) {
  474. this.node.forward = normalizedDir.negative();
  475. }
  476. } else {
  477. //到达当前路径点后指向下一个点
  478. this.curMoveIndex++;
  479. if (this.curMoveIndex < this.pathList.length) {
  480. const nextTarget = this.pathList[this.curMoveIndex];
  481. Vec3.subtract(moveDirection, nextTarget, currentPos);
  482. this.node.forward = moveDirection.normalize().negative();
  483. }
  484. }
  485. //到达路径终点处理
  486. if (this.curMoveIndex >= this.pathList.length) {
  487. this.beginFire();
  488. this.skeletalAnim.play(EAnimType.shoot);
  489. this.updateDir(this.node.worldPosition.clone());
  490. }
  491. }
  492. /**
  493. * 更新敌人方向
  494. * @param curPos 位置
  495. */
  496. public updateDir(curPos: Vec3){
  497. const direction = Vec3.subtract(new Vec3(), curPos, Game.I.player.node.worldPosition);
  498. direction.normalize();
  499. this.node.forward = direction;
  500. }
  501. /**
  502. * 是否是坦克
  503. */
  504. public isTank():boolean{
  505. return this.data.id == EnemyType.Tank;
  506. }
  507. }
  508. /**
  509. *
  510. if (this.isDead
  511. || !this.player) return;
  512. if (!this.isAlert) {
  513. this.skeletalAnim.play(EAnimType.walk);
  514. const playerPos = this.player.node.getWorldPosition();
  515. const enemyPos = this.node.getWorldPosition();
  516. //创建射线对象修复类型错误
  517. const ray = new geometry.Ray();
  518. ray.o = enemyPos;
  519. ray.d = playerPos.subtract(enemyPos).normalize();
  520. //修正物理检测参数
  521. if (PhysicsSystem.instance.raycast(ray, 1 << 0, 2)) {
  522. const randomDir = Math.random() > 0.5 ? 1 : -1;
  523. //修改为正确的参数格式
  524. const quat = new Quat();
  525. Quat.fromAxisAngle(quat, Vec3.UP, 45 * randomDir * Math.PI / 180);
  526. this.node.rotate(quat, NodeSpace.WORLD);
  527. }
  528. //this.skeletalAnim.play("walk");
  529. //使用定时器持续移动
  530. this.schedule(() => {
  531. const distance: number = Vec3.distance(this.node.worldPosition,Game.I.buildEnemys.ambush.worldPosition);
  532. if(distance < 10) {
  533. this.isAlert = true;
  534. this.walk();
  535. return;
  536. }
  537. const moveVec = this.node.forward.negative().multiplyScalar(this.speed * 0.016);
  538. this.node.position = this.node.position.add(moveVec);
  539. }, 0.1);
  540. } else if (!this.currentCover) {
  541. const nearestCover = this.findNearestCover();
  542. if (nearestCover) {
  543. this.currentCover = nearestCover;
  544. //生成Z轴随机偏移(-18到+18)
  545. const targetPos = nearestCover.worldPosition.clone();
  546. targetPos.z += Math.random() * 36 - 18;
  547. //移动到掩体位置 直接使用缓动动画移动到掩体
  548. tween(this.node)
  549. .to(2, { worldPosition: targetPos }, {
  550. easing: easing.quadOut,
  551. onStart: () => {
  552. this.speed = this.defaultSpeed * 1.5; //加速移动
  553. },
  554. onComplete: () => {
  555. this.skeletalAnim.play(EAnimType.shoot);
  556. this.beginFire(); //到达后开始攻击
  557. this.currentCover = nearestCover;
  558. }
  559. })
  560. .start();
  561. }
  562. }
  563. */