Enemy.ts 20 KB

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