GunfightShootUI.ts 18 KB

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