LevelAction.ts 13 KB

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