LevelAction.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import { _decorator, BoxCollider2D, Button, Camera, CCFloat, CircleCollider2D, Color, Component, debug, DebugView, director, EventTouch, find, geometry, Input, input, Label, math, Node, NodeEventType, PhysicsSystem, Quat, RenderTexture, Tween, tween, v3, Vec3, view } from 'cc';
  2. import { EventDispatcher } from '../../core_tgx/easy_ui_framework/EventDispatcher';
  3. import { GameEvent } from './Enum/GameEvent';
  4. import { LineDrawer } from './LineDrawer';
  5. import { EnemyComponent } from './Components/EnemyComponent';
  6. import { AliensGlobalInstance } from './AliensGlobalInstance';
  7. import { ScreenShotComponent } from './Components/ScreenShotComponent';
  8. import { GameUtil } from './GameUtil';
  9. import { RadarComponent } from './Components/RadarComponent';
  10. import { tgxUIMgr } from '../../core_tgx/tgx';
  11. import { UI_BattleGambit } from '../../scripts/UIDef';
  12. import { CameraSegmentation, moveDuration } from './CamerSegmentation';
  13. import { TimerMgr } from './Manager/TimerMgr';
  14. import { LevelManager } from './Manager/LevelMgr';
  15. import { CAMERA_SPLIT_DURATION } from './Components/BulletComponent';
  16. import { AliensAudioMgr } from './Manager/AliensAudioMgr';
  17. const { ccclass, property } = _decorator;
  18. //动画时长
  19. export const ANIMATION_DURATION = 0.5;
  20. @ccclass('LevelAction')
  21. export class LevelAction extends Component {
  22. @property(Camera)
  23. public camera: Camera = null!;
  24. private _renderTex: RenderTexture | null = null;
  25. private _isZooming = false;
  26. public targetNode: Node = null!;
  27. //关卡怪物总数
  28. @property({ type: CCFloat, displayName: "怪物总数" })
  29. public enemyTotal: number = 0;
  30. @property({ type: CCFloat, displayName: "拉近镜头的距离" })
  31. zoomDistance: number = 10; //拉近镜头的距离
  32. @property({ type: CCFloat, displayName: "旋转速度" })
  33. rotateSpeed: number = 0.2;
  34. // 添加旋转限制属性
  35. @property({ type: CCFloat, displayName: "水平旋转限制角度" })
  36. horizontalLimit: number = 50; // 水平旋转限制角度(左右各50度)
  37. @property({ type: CCFloat, displayName: "垂直旋转限制角度" })
  38. @property
  39. verticalLimit: number = 30; // 垂直旋转限制角度(上下各30度)
  40. private _initialRotation: Vec3 = new Vec3(0, 0, 0); // 初始旋转角度
  41. private _initialPosition: Vec3 = new Vec3();
  42. private _isZoomed: boolean = false; // 记录是否处于拉近状态
  43. onLoad(): void {
  44. this.camera.node.rotation.getEulerAngles(this._initialRotation);
  45. this._initialPosition = this.camera.node.position.clone();
  46. this.registerEvent();
  47. }
  48. start() {
  49. this.initilizeUI();
  50. this.saveCameraState();
  51. EventDispatcher.instance.emit(GameEvent.EVENT_INIT_REMAIN_ENEMY, this.enemyTotal);
  52. }
  53. private initilizeUI() {
  54. const renderNode = AliensGlobalInstance.instance.renderNode;
  55. const aimTarget = AliensGlobalInstance.instance.aimTarget;
  56. const radarNode = AliensGlobalInstance.instance.radarNode;
  57. renderNode.active = false;
  58. aimTarget.active = false;
  59. radarNode.active = false;
  60. const match = tgxUIMgr.inst.isShowing(UI_BattleGambit);
  61. if (!match) {
  62. tgxUIMgr.inst.showUI(UI_BattleGambit);
  63. }
  64. this.updateLvlTitle();
  65. }
  66. private updateLvlTitle() {
  67. const lvlTitle = AliensGlobalInstance.instance.titleLvl;
  68. const level = LevelManager.instance.levelModel.level;
  69. lvlTitle.getChildByName('LbLvl').getComponent(Label).string = `${level}`;
  70. }
  71. private registerEvent() {
  72. // 触摸事件监听
  73. input.on(Input.EventType.TOUCH_START, this._onTouchStart, this);
  74. input.on(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
  75. input.on(Input.EventType.TOUCH_END, this._onTouchEnd, this);
  76. input.on(Input.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
  77. //事件监听
  78. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_AIM, this.onAimTarget, this);
  79. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_RESET_AIM, this.onResetAimTarget, this);
  80. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_SHOOT, this.onShoot, this);
  81. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_SCREENSHOT_RADAR_LOCK, this.onCameraToTarget, this);
  82. }
  83. private unRegisterEvent() {
  84. // 触摸事件监听
  85. input.off(Input.EventType.TOUCH_START, this._onTouchStart, this);
  86. input.off(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
  87. input.off(Input.EventType.TOUCH_END, this._onTouchEnd, this);
  88. input.off(Input.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
  89. //事件监听
  90. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_AIM, this.onAimTarget, this);
  91. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_RESET_AIM, this.onResetAimTarget, this);
  92. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_SHOOT, this.onShoot, this);
  93. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_SCREENSHOT_RADAR_LOCK, this.onCameraToTarget, this);
  94. }
  95. private onAimTarget() {
  96. if (this._isZoomed) return;
  97. // 获取相机前方方向(世界坐标)
  98. const forward = new Vec3(0, 0, -1);
  99. Vec3.transformQuat(forward, forward, this.camera.node.rotation);
  100. // 朝前方移动(拉近)
  101. Vec3.scaleAndAdd(this.camera.node.position, this._initialPosition, forward, this.zoomDistance);
  102. this.camera.node.setPosition(this.camera.node.position);
  103. this._isZoomed = true;
  104. }
  105. private onResetAimTarget() {
  106. if (!this._isZoomed) return;
  107. // 恢复到初始位置但保持当前旋转角度
  108. const currentRotation = new Vec3();
  109. this.camera.node.rotation.getEulerAngles(currentRotation);
  110. this.camera.node.setPosition(this._initialPosition);
  111. // 保持旋转角度不变
  112. const rotation = new Quat();
  113. Quat.fromEuler(rotation, currentRotation.x, currentRotation.y, 0);
  114. this.camera.node.setRotation(rotation);
  115. this._isZoomed = false;
  116. }
  117. private async onShoot() {
  118. // 获取正确的屏幕中心坐标
  119. const screenCenter = view.getVisibleSize();
  120. const screenX = screenCenter.width * 0.5 * view.getScaleX();
  121. const screenY = screenCenter.height * 0.5 * view.getScaleY();
  122. // 从屏幕中心发射射线
  123. const ray = new geometry.Ray();
  124. this.camera.screenPointToRay(screenX, screenY, ray);
  125. // 射线检测参数
  126. const mask = 0xffffffff;
  127. const maxDistance = 1000;
  128. const queryTrigger = true;
  129. // 执行射线检测
  130. const hasHit = PhysicsSystem.instance.raycast(ray, mask, maxDistance, queryTrigger);
  131. if (hasHit) {
  132. const results = PhysicsSystem.instance.raycastResults;
  133. for (let i = 0; i < results.length; i++) {
  134. const item = results[i];
  135. const hitNode = item.collider.node;
  136. if (item.collider.getGroup() == 1 << 4) {
  137. LevelManager.instance.levelModel.headshotCount++;
  138. // console.log('爆头了!!!!!!!!!!!!');
  139. EventDispatcher.instance.emit(GameEvent.EVENT_CAMERA_HEADSHOT); // 触发事件通知UI显示headshot di
  140. }
  141. if (hitNode.getComponent(EnemyComponent)) {
  142. LevelManager.instance.levelModel.hitCount++;
  143. // console.log(`击中次数: ${LevelManager.instance.levelModel.hitCount} 爆头次数: ${LevelManager.instance.levelModel.headshotCount}`)
  144. const levelNode = AliensGlobalInstance.instance.levels.children[0];
  145. const remain = levelNode.getChildByName('Ets')!.children.length;
  146. if (remain > 1) {
  147. AliensAudioMgr.playOneShot(AliensAudioMgr.getMusicIdName(5), 1.0);
  148. EventDispatcher.instance.emit(GameEvent.EVENT_CAMERA_SHOOT_ENEMY, hitNode);
  149. } else {
  150. EventDispatcher.instance.emit(GameEvent.EVENT_LAST_ENEMY_KILLED);
  151. TimerMgr.inst.pauseCountdown();
  152. EventDispatcher.instance.emit(GameEvent.EVENT_CAMERA_SPLIT, hitNode);
  153. this.scheduleOnce(() => {
  154. EventDispatcher.instance.emit(GameEvent.EVENT_CAMERA_SHOOT_ENEMY, hitNode);
  155. }, CAMERA_SPLIT_DURATION);
  156. }
  157. }
  158. }
  159. }
  160. EventDispatcher.instance.emit(GameEvent.EVENT_PLAY_GUN_ANIMATION);
  161. LevelManager.instance.levelModel.shootCount++;
  162. }
  163. //相机转向目标
  164. private async onCameraToTarget(targetNode: Node) {
  165. const camera = this.camera;
  166. if (!targetNode || !camera) return;
  167. const targetPos = new Vec3();
  168. targetNode.getWorldPosition(targetPos);
  169. // 获取相机位置
  170. const cameraPos = new Vec3();
  171. camera.node.getWorldPosition(cameraPos);
  172. // 计算从相机到目标的方向向量
  173. const direction = new Vec3();
  174. Vec3.subtract(direction, targetPos, cameraPos);
  175. direction.normalize();
  176. // 计算目标欧拉角
  177. const targetYaw = math.toDegree(Math.atan2(-direction.x, -direction.z));
  178. const targetPitch = math.toDegree(Math.asin(direction.y));
  179. // 获取当前欧拉角
  180. const currentRotation = camera.node.eulerAngles.clone();
  181. // 创建一个对象用于tween
  182. const tweenObj = {
  183. pitch: currentRotation.x,
  184. yaw: currentRotation.y
  185. };
  186. this._isZoomed = true;
  187. tween(tweenObj)
  188. .to(ANIMATION_DURATION, {
  189. pitch: targetPitch,
  190. yaw: targetYaw
  191. }, {
  192. easing: 'smooth',
  193. onUpdate: () => {
  194. // 更新相机旋转
  195. camera.node.setRotationFromEuler(tweenObj.pitch, tweenObj.yaw, 0);
  196. },
  197. onComplete: () => {
  198. this._isZoomed = false;
  199. }
  200. })
  201. .start();
  202. }
  203. /***************************触摸事件**********************************/
  204. private _onTouchStart(event: EventTouch) {
  205. const radarComponent = AliensGlobalInstance.instance.renderNode.getComponent(RadarComponent)!;
  206. if (radarComponent) {
  207. radarComponent.unlockPositionUpdate();
  208. }
  209. }
  210. private async _onTouchMove(event: EventTouch) {
  211. const delta = event.getDelta();
  212. // 获取当前相机旋转
  213. const currentRotation = new Vec3();
  214. this.camera.node.rotation.getEulerAngles(currentRotation);
  215. // 计算新角度
  216. currentRotation.y -= delta.x * this.rotateSpeed;
  217. currentRotation.x += delta.y * this.rotateSpeed;
  218. // 限制水平旋转角度(基于初始角度)
  219. currentRotation.y = Math.max(
  220. this._initialRotation.y - this.horizontalLimit,
  221. Math.min(this._initialRotation.y + this.horizontalLimit, currentRotation.y)
  222. );
  223. // 限制垂直旋转角度(基于初始角度)
  224. currentRotation.x = Math.max(
  225. this._initialRotation.x - this.verticalLimit,
  226. Math.min(this._initialRotation.x + this.verticalLimit, currentRotation.x)
  227. );
  228. // 应用旋转
  229. const rotation = new Quat();
  230. Quat.fromEuler(rotation, currentRotation.x, currentRotation.y, 0);
  231. this.camera.node.setRotation(rotation);
  232. await this.saveCameraState();
  233. }
  234. //保存相机的位置和旋转角度
  235. private async saveCameraState() {
  236. const cameraOriginalPos = this.camera.node.worldPosition.clone();
  237. const originalRotation = this.camera.node.eulerAngles.clone();
  238. const screenShot = AliensGlobalInstance.instance.renderNode.getComponent(ScreenShotComponent)!;
  239. screenShot.saveCameraState(cameraOriginalPos, originalRotation);
  240. }
  241. private _onTouchEnd() {
  242. const radarComponent = AliensGlobalInstance.instance.renderNode.getComponent(RadarComponent)!;
  243. if (radarComponent) {
  244. radarComponent.unlockPositionUpdate();
  245. }
  246. }
  247. /***************************触摸事件end**********************************/
  248. onDestroy() {
  249. Tween.stopAllByTarget(this.node);
  250. this.unRegisterEvent();
  251. if (this._renderTex) {
  252. this._renderTex.destroy();
  253. this._renderTex = null;
  254. }
  255. }
  256. }