Enemy.ts 19 KB

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