GunfightShootUI.ts 19 KB

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