LevelAction.ts 13 KB

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