GunfightShootUI.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. import { _decorator, EventTouch, Node, Quat, math, Camera, sys, Vec3, Label, geometry, ProgressBar, tween, easing, Tween, UIOpacity, game, PhysicsSystem, PhysicsRayResult } from 'cc';
  2. import { Game } from '../game/Game';
  3. import { BaseExp } from '../core/base/BaseExp';
  4. import { autoBind } from '../extend/AutoBind';
  5. import { Constants } from '../data/Constants';
  6. import { uiMgr } from '../core/manager/UIManager';
  7. import { userIns } from '../data/UserData';
  8. import MsgHints from '../utils/MsgHints';
  9. import List from '../third/List';
  10. import { Utils } from '../utils/Utils';
  11. import { TaskEnemyItem } from '../items/item/TaskEnemyItem';
  12. import { BulletMagazine } from '../game/BulletMagazine';
  13. import { audioMgr } from '../core/manager/AudioManager';
  14. import { settingData } from '../data/SettingData';
  15. import i18n from '../core/i18n/runtime-scripts/LanguageData';
  16. import { Main } from '../game/Main';
  17. const { ccclass, property } = _decorator;
  18. const { clamp, toRadian } = math;
  19. @ccclass('GunfightShootUI')
  20. export class GunfightShootUI extends BaseExp {
  21. @autoBind({ type: Node, tooltip: "轮盘节点" })
  22. public wheel: Node;
  23. @autoBind({ type: Node, tooltip: "标准贴图" })
  24. public scopeOverlay: Node;
  25. @autoBind({ type: Node, tooltip: "准心" })
  26. public crossHair: Node;
  27. @autoBind({ type: ProgressBar, tooltip: "步枪子弹进度条" })
  28. public rifle_bullet_progressBar: ProgressBar;
  29. @autoBind({ type: Label, tooltip: "步枪子弹数文本" })
  30. public rifle_bullet_num_label: Label;
  31. @autoBind({ type: BulletMagazine, tooltip: "步枪子弹列表" })
  32. public rifle_bullets_scrollView: BulletMagazine;
  33. @autoBind({ type: BulletMagazine, tooltip: "狙击枪子弹列表" })
  34. public snipe_bullets_scrollView: BulletMagazine;
  35. @autoBind({ type: Node, tooltip: "步枪显示子弹的总的节点" })
  36. public rifle_bullets_bg: Node;
  37. @autoBind({ type: List, tooltip: "敌人任务列表" })
  38. public task_scrollView: List;
  39. @autoBind({ type: ProgressBar, tooltip: "玩家生命进度条" })
  40. public hpProgressBar: ProgressBar;
  41. @property({type: [Node], tooltip: "要隐藏的所有按钮"})
  42. public hiddeNodes: Array<Node> = [];
  43. @autoBind({ type: ProgressBar, tooltip: "换弹夹时间进度条" })
  44. public reloadProgressBar: ProgressBar;
  45. @autoBind({ type: Node, tooltip: "玩家受到伤害呼吸闪烁" })
  46. public injury_blood: Node;
  47. @autoBind({ type: Label, tooltip: "玩家枪的名字" })
  48. public gun_name_label: Label;
  49. @autoBind({ type: Label, tooltip: "关卡名字" })
  50. public gk_num_lable: Label;
  51. /** 子弹飞行距离 */
  52. public bulletDistance: number = 800;
  53. /** 当前相机绕 X 轴的旋转角度 */
  54. private currentXRotation: number = 0;
  55. /** 当前相机绕 Y 轴的旋转角度 */
  56. private currentYRotation: number = 0;
  57. /** 左右旋转角度的最大限制值 */
  58. private maxHorizontalAngle: number = 70;
  59. /** 上下旋转角度的最大限制值 */
  60. private maxVerticalAngle: number = 70;
  61. /** 相机的原始视野值 */
  62. private originalFov: number;
  63. /** 玩家节点的初始旋转四元数 */
  64. private initialPlayerRotation: Quat = new Quat();
  65. /** 相机节点的初始旋转四元数 */
  66. private initialCameraRotation: Quat = new Quat();
  67. /** 相机放大后的目标视野值 */
  68. private targetFov: number;
  69. /** 标记相机是否正在进行放大操作 */
  70. private isZoomingIn: boolean = false;
  71. /** 标记相机是否正在进行缩小操作 */
  72. private isZoomingOut: boolean = false;
  73. /** 相机视野放大的速度 */
  74. private zoomSpeed: number = 0;
  75. /** 期望的缩放时间,单位为秒 */
  76. private zoomDuration: number = 0.2;
  77. /** 记录镜头开始放大的时间 */
  78. private zoomStartTime: number = 0;
  79. /** 标记是否在2秒内完成放大 */
  80. private zoomValid: boolean = false;
  81. /** 标记是否开镜 */
  82. private _isScopeOpen: boolean = false;
  83. get isScopeOpen() {
  84. return this._isScopeOpen;
  85. }
  86. set isScopeOpen(value: boolean) {
  87. this.gunDataUI();
  88. if (this._isScopeOpen !== value) {
  89. this._isScopeOpen = value;
  90. if (value) {
  91. this.openScope();
  92. } else {
  93. this.closeScope();
  94. }
  95. }
  96. }
  97. /**镜头的位置*/
  98. private wheelPos: Vec3 = Vec3.ZERO;
  99. //任务数据
  100. private taskDatas: Array<any> = [];
  101. //是否正在被击中
  102. private isHurtRun: boolean = false;
  103. start() {
  104. this.hasAnim = false;
  105. this.closeOnBlank = false;
  106. this.injury_blood.active = false;
  107. this.reloadProgressBar.node.active = false;
  108. if(!Constants.isDebug){
  109. this.hiddeNodes.forEach(e => e.active = false);
  110. }
  111. this.wheelPos = this.wheel.position.clone();
  112. //监听当前节点触摸事件
  113. this.node.on(Node.EventType.TOUCH_START, this.onNodeTouchMove, this);
  114. this.node.on(Node.EventType.TOUCH_MOVE, this.onNodeTouchMove, this);
  115. this.node.on(Node.EventType.TOUCH_END, this.onCustomNodeTouchEnd, this);
  116. this.node.on(Node.EventType.TOUCH_CANCEL, this.onCustomNodeTouchEnd, this);
  117. //监听轮盘点击事件 监听轮盘的触摸开始事件,当触摸开始时调用 onWheelClick 方法
  118. this.wheel.on(Node.EventType.TOUCH_START, this.onWheelClick, this);
  119. this.wheel.on(Node.EventType.TOUCH_END, this.onWheelRelease, this);
  120. this.wheel.on(Node.EventType.TOUCH_CANCEL, this.onWheelRelease, this);
  121. //敌人数量改变
  122. this.register(Constants.eventName.enemy_num_change, this.loadTaskData.bind(this));
  123. }
  124. public hide(){
  125. uiMgr.getPageComponent(Constants.mainUIs.main)?.playOrStopBGM(false);
  126. }
  127. /**
  128. * 摄像机初始信息
  129. * @param args
  130. */
  131. public originalInitial(){
  132. //记录摄像机原始视野
  133. this.originalFov = Game.I.camera.getComponent(Camera).fov;
  134. //录初始旋转角度
  135. this.initialPlayerRotation = Game.I.player.node.rotation.clone();
  136. this.initialCameraRotation = Game.I.camera.node.rotation.clone();
  137. this.currentYRotation = this.initialPlayerRotation.x;
  138. this.currentXRotation = this.initialPlayerRotation.y;
  139. }
  140. public show(...args: any[]){
  141. this.loadTaskData();
  142. }
  143. /**
  144. * enemyId total count enemyData
  145. * 加载数据
  146. */
  147. public loadTaskData() {
  148. const data: any = userIns.getCurLevelData();
  149. this.gk_num_lable.string = i18n("main.关卡任务 %{value}",{value: data.id});
  150. this.taskDatas = Game.I.buildEnemys.enemyTypeRecords;
  151. this.task_scrollView.numItems = this.taskDatas.length;
  152. //加载子弹的数据
  153. this.gunDataUI();
  154. }
  155. /**
  156. * 任务数据
  157. * @param item item节点
  158. * @param idx 数据下标
  159. */
  160. public setTaskItemData(item: Node, idx: number) {
  161. item.getComponent(TaskEnemyItem).init(this.taskDatas[idx]);
  162. }
  163. /**
  164. * 设置枪的数据
  165. */
  166. public gunDataUI() {
  167. const gData:any = Game.I.player.pData;
  168. if(Game.I.isGameOver
  169. || Game.I.isPause
  170. || !Game.I.player.gun
  171. || !gData){
  172. return;
  173. }
  174. this.crossHair.active = true;//准心
  175. //步枪没有开镜贴图
  176. this.scopeOverlay.active = !this.isRifleGun();
  177. this.gun_name_label.string = gData.name_lang;
  178. const isSnipeGun: boolean = gData.type == 1;
  179. //换弹夹进度条
  180. const isMagazine: boolean = Game.I.player.isReloadMagazine;
  181. if(isMagazine){
  182. this.rifle_bullets_bg.active = false;
  183. this.snipe_bullets_scrollView.node.active = false;
  184. }else{
  185. //步枪子弹视图
  186. this.rifle_bullets_bg.active = !isSnipeGun;
  187. //狙击子弹视图列表
  188. this.snipe_bullets_scrollView.node.active = isSnipeGun;
  189. if(isSnipeGun){
  190. this.snipe_bullets_scrollView.magazineNum = gData.magazine;
  191. }else{
  192. this.rifle_bullets_scrollView.magazineNum = gData.magazine;
  193. //子弹进度条
  194. let s_bullet: number = gData.magazine - Game.I.player.gun.shotBullets;
  195. this.rifle_bullet_progressBar.progress = s_bullet / gData.magazine;
  196. this.rifle_bullet_num_label.string = `${s_bullet}/${gData.magazine}`;
  197. }
  198. }
  199. }
  200. /**
  201. * 更换弹夹动画
  202. * @param time 换弹时间 单位秒
  203. * @param complete 完成回调
  204. */
  205. public reloadMagazineing(time: number,complete?: Function) {
  206. if(time <= 0){
  207. complete?.();
  208. }else{
  209. this.reloadProgressBar.node.active = true;
  210. this.reloadProgressBar.progress = 1;
  211. this.rifle_bullets_bg.active = false;
  212. this.snipe_bullets_scrollView.node.active = false;
  213. //创建定时器动画
  214. tween(this.reloadProgressBar)
  215. .to(time, { progress: 0 }, {
  216. easing: easing.linear,
  217. onStart: () => {
  218. tween(this.reloadProgressBar).stop();
  219. },
  220. onComplete: () => {
  221. this.reloadProgressBar.node.active = false;
  222. complete?.();
  223. }
  224. })
  225. .start();
  226. }
  227. }
  228. /**
  229. * 根据切换枪的stability设置镜头的稳定性
  230. */
  231. public crossHairStability() {
  232. const gData:any = Game.I.player.pData;
  233. if(!gData)return;
  234. this.gunDataUI();
  235. this.wheel.position = this.wheelPos;
  236. //参数映射优化(假设stability范围0-1) 振幅稳定性越低振幅越大 频率稳定性越低抖动越快
  237. const amplitude = 20 * (1 - gData.stability / 1000);
  238. let elapsed = 0;
  239. //基础抖动持续时间
  240. const duration = 0.4;
  241. const updateShake = (deltaTime: number) => {
  242. elapsed += deltaTime;
  243. //双轴随机偏移
  244. const offsetX = amplitude * (Math.random() - 0.5) * Math.max(1 - elapsed/duration, 0);
  245. const offsetY = amplitude * (Math.random() - 0.5) * Math.max(1 - elapsed/duration, 0);
  246. this.wheel.position = new Vec3(
  247. this.wheelPos.x + offsetX,
  248. this.wheelPos.y + offsetY,
  249. this.wheelPos.z
  250. );
  251. //自动结束
  252. if(elapsed >= duration) {
  253. this.wheel.position = this.wheelPos;
  254. this.unschedule(updateShake);
  255. }
  256. };
  257. this.unschedule(updateShake);
  258. // 使用游戏时间而非系统时间
  259. this.schedule(updateShake, 0.02); // 每0.02秒更新(约50FPS)
  260. }
  261. /**
  262. * 屏幕触摸事件
  263. * 触摸移动时,根据触摸的位置计算旋转角度,并应用到节点上
  264. * @param event
  265. */
  266. private onNodeTouchMove(event: EventTouch) {
  267. const delta = event.getDelta();
  268. let f: number = this._isScopeOpen ? 0.2 : 0.6;
  269. //计算旋转角度 相机旋转的灵敏度 值越大移动越快 灵敏度越高
  270. this.currentYRotation -= delta.x * settingData.data.sensitivity * f;
  271. this.currentXRotation -= delta.y * settingData.data.sensitivity * f;
  272. //分别限制左右和上下旋转角度
  273. this.currentYRotation = clamp(this.currentYRotation, -this.maxHorizontalAngle, this.maxHorizontalAngle);
  274. this.currentXRotation = clamp(this.currentXRotation, -this.maxVerticalAngle, this.maxVerticalAngle);
  275. //计算水平和垂直旋转的四元数
  276. const yQuat = new Quat();
  277. Quat.fromEuler(yQuat, 0, this.currentYRotation, 0);
  278. const xQuat = new Quat();
  279. Quat.fromEuler(xQuat, +this.currentXRotation, 0, 0);
  280. //合并旋转
  281. let finalQuat = new Quat();
  282. Quat.multiply(finalQuat, yQuat, xQuat);
  283. //将最终旋转与初始摄像机旋转合并
  284. Quat.multiply(finalQuat, this.initialPlayerRotation, finalQuat);
  285. //应用旋转到摄像机
  286. Game.I.player.node.rotation = finalQuat;
  287. }
  288. /**
  289. * 触摸结束
  290. * 触摸结束时 触摸结束处理方法
  291. */
  292. private onCustomNodeTouchEnd() {
  293. //触摸结束,可添加其他逻辑
  294. }
  295. /**
  296. * 开始慢慢放大视野
  297. */
  298. private onWheelClick() {
  299. this.isScopeOpen = true;
  300. }
  301. /**
  302. * 恢复原始视野
  303. */
  304. private onWheelRelease() {
  305. if(!this.zoomValid){
  306. this.isScopeOpen = false;
  307. return
  308. }
  309. //是步枪直接连续开火
  310. if(!this.isRifleGun()){
  311. Game.I.player.shoot();
  312. this.scheduleOnce(()=>{
  313. //检查是否在秒内完成放大 已经在update里开镜完成时调用 Game.I.player.shoot();
  314. this.isScopeOpen = false;
  315. },0.6)
  316. }else{
  317. this.isScopeOpen = false;
  318. }
  319. }
  320. /**
  321. * 开始开镜
  322. */
  323. private openScope() {
  324. //从枪械数据获取参数
  325. const gData = Game.I.player.pData;
  326. if(!gData)return;
  327. const isRifle: boolean = this.isRifleGun();
  328. //是步枪直接连续开火
  329. if(isRifle){
  330. Game.I.player.shoot();
  331. }
  332. this.isZoomingIn = true;
  333. //将 zoomingSpeed 转换为持续时间(450对应1.2秒)
  334. this.zoomDuration = 72 / gData.zoomingSpeed;
  335. //使用枪械类型决定视口倍数 步枪使用 rifleZoom 狙击枪使用 scopeZoom
  336. const zoomMultiplier = isRifle ?
  337. 1 / gData.rifleZoom :
  338. 1 / gData.scopeZoom;
  339. this.targetFov = this.originalFov * zoomMultiplier;
  340. //保持原有速度计算逻辑
  341. const fovDifference = this.originalFov - this.targetFov;
  342. this.zoomSpeed = fovDifference / this.zoomDuration;
  343. this.zoomStartTime = sys.now();
  344. }
  345. /**
  346. * 关闭开镜
  347. */
  348. private closeScope() {
  349. this.isZoomingIn = false;
  350. this.isZoomingOut = true;
  351. const fovDifference = this.originalFov - this.targetFov;
  352. //使用相同 zoomDuration 保证缩镜速度一致
  353. this.zoomSpeed = fovDifference / this.zoomDuration;
  354. }
  355. /**
  356. * 是否是步枪
  357. */
  358. public isRifleGun(){
  359. const gData:any = Game.I.player.pData;
  360. if(!gData)return false;
  361. return gData.id == '100014' || gData.id == '100015';
  362. }
  363. /**
  364. * 计算从枪口出发,沿准心射线方向的点
  365. * @param isBulletEndPos 是否获得子弹的终点
  366. */
  367. public getCrossHairPos(){
  368. //获取屏幕准心位置(世界坐标)
  369. const screenPos = this.getScreenCenterPos();
  370. //校准补偿准心的偏移量
  371. //screenPos.x -= 0;
  372. //screenPos.y += 0;
  373. //从摄像机发射通过准心的射线
  374. const ray = new geometry.Ray();
  375. Game.I.camera.screenPointToRay(screenPos.x, screenPos.y, ray);
  376. //获取枪口位置
  377. const muzzlePos = Game.I.player.gun.muzzleNode.worldPosition;
  378. return new Vec3(
  379. muzzlePos.x + ray.d.x * this.bulletDistance,
  380. muzzlePos.y + ray.d.y * this.bulletDistance,
  381. muzzlePos.z + ray.d.z * this.bulletDistance);
  382. }
  383. /**
  384. * 返回屏幕中心的世界坐标
  385. */
  386. public getScreenCenterPos(){
  387. const worldPos = this.crossHair.worldPosition.clone();
  388. const camera2D: Camera = Game.I.canvas.getChildByName('Camera2D').getComponent(Camera);
  389. let screenPos = camera2D.worldToScreen(worldPos);
  390. return screenPos;
  391. }
  392. /**
  393. * 玩家血量低于30%一直闪烁、打一枪的时候闪一下
  394. * @param progress 血量进度
  395. * @returns
  396. */
  397. public playerHurtTwinkle(progress: number){
  398. this.hpProgressBar.progress = progress;
  399. const isLowHP = progress <= 0.3;
  400. const op = this.injury_blood.getComponent(UIOpacity);
  401. //如果当前是高血量且正在闪烁 停止并隐藏
  402. if (!isLowHP && this.isHurtRun) {
  403. this.isHurtRun = false;
  404. Tween.stopAllByTarget(op);
  405. this.injury_blood.active = false;
  406. return;
  407. }
  408. if (isLowHP && !this.isHurtRun) {//低血量且未在闪烁时,启动循环闪烁
  409. this.isHurtRun = true;
  410. this.injury_blood.active = true;
  411. op.opacity = 255;
  412. tween(op)
  413. .to(0.5, { opacity: 0 }, { easing: easing.linear })
  414. .to(0.5, { opacity: 255 }, { easing: easing.linear })
  415. .repeatForever()
  416. .start();
  417. }else if (!isLowHP) {//高血量时触发单次闪烁
  418. this.injury_blood.active = true;
  419. Tween.stopAllByTarget(op);
  420. op.opacity = 255;
  421. tween(op)
  422. .to(0.4, { opacity: 0 }, { easing: easing.linear })
  423. .call(() => {
  424. this.injury_blood.active = false;
  425. })
  426. .start();
  427. }
  428. }
  429. /**
  430. * 点击事件
  431. * @param event 事件
  432. * @param customEventData 数据
  433. */
  434. public onBtnClicked(event: EventTouch, customEventData: any) {
  435. super.onBtnClicked(event,customEventData);
  436. let btnName = event.target.name;
  437. if (btnName === 'pause_btn') { // 暂停页面
  438. uiMgr.show(Constants.popUIs.pauseUI);
  439. }else if (btnName === 'shot_btn') {//射击
  440. if(this.isRifleGun){
  441. //模拟按下射击
  442. this._isScopeOpen = true;
  443. Game.I.player.shoot();
  444. this.scheduleOnce(()=>{
  445. this._isScopeOpen = false;
  446. },1.5)
  447. }else{
  448. Game.I.player.shoot();
  449. }
  450. }else if (btnName === 'cut_gun_btn') {//切枪
  451. Game.I.player.randomCutGun()
  452. }else if(btnName === 'clean_btn'){//重新加载数据
  453. userIns.removeData();
  454. Game.I.player.pData = userIns.getCurUseGun();
  455. MsgHints.show('重新加载数据完成');
  456. }else if(btnName === 'unlock_btn'){//解锁全部枪数据
  457. userIns.unlockAllGuns();
  458. MsgHints.show('已经解锁全部枪数据');
  459. }
  460. }
  461. /**
  462. * 每帧更新,处理视野渐变和检查 2 秒时间限制
  463. * @param deltaTime - 上一帧到当前帧的时间间隔
  464. */
  465. update(deltaTime: number) {
  466. if (this.isZoomingIn) {
  467. const currentFov = Game.I.camera.fov;
  468. if (currentFov > this.targetFov) {
  469. const newFov = currentFov - this.zoomSpeed * deltaTime;
  470. Game.I.camera.fov = Math.max(newFov, this.targetFov);
  471. } else {
  472. //检查是否在2秒内完成放大
  473. const elapsedTime = (sys.now() - this.zoomStartTime) / 1000;
  474. if (elapsedTime <= 1.5) {
  475. this.zoomValid = true;
  476. }
  477. this.isZoomingIn = false;
  478. }
  479. } else if (this.isZoomingOut) {
  480. const currentFov = Game.I.camera.fov;
  481. if (currentFov < this.originalFov) {
  482. const newFov = currentFov + this.zoomSpeed * deltaTime;
  483. Game.I.camera.fov = Math.min(newFov, this.originalFov);
  484. } else {
  485. this.isZoomingOut = false;
  486. this.zoomValid = false;
  487. }
  488. }
  489. }
  490. }