LevelAction.ts 12 KB

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