LevelAction.ts 14 KB

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