LevelAction.ts 14 KB

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