GunfightShootUI.ts 18 KB

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