LevelAction.ts 12 KB

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