LevelAction.ts 14 KB

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