LevelAction.ts 11 KB

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