Enemy.ts 19 KB

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