LevelAction.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. const { ccclass, property } = _decorator;
  13. enum ERaycastType {
  14. ALL,
  15. CLOSEST
  16. }
  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 _cameraOriginalPos: Vec3 = v3();
  23. private _touchStartPos: Vec3 = v3();
  24. private _isDragging = false;
  25. private _isZooming = false;
  26. public targetNode: Node = null!;
  27. // 添加旋转限制属性
  28. @property({type: CCFloat ,displayName:"相机X轴最小旋转角度(上下)"})
  29. public minXRotation: number = -30; // X轴最小旋转角度(上下)
  30. @property({type: CCFloat ,displayName:"相机X轴最大旋转角度(上下)"})
  31. public maxXRotation: number = 30; // X轴最大旋转角度(上下)
  32. @property({type: CCFloat ,displayName:"相机Y轴最小旋转角度(左右)"})
  33. public minYRotation: number = -50; // Y轴最小旋转角度(左右)
  34. @property({type: CCFloat ,displayName:"相机Y轴最大旋转角度(左右)"})
  35. public maxYRotation: number = 50; // Y轴最大旋转角度(左右)
  36. private _originalRotation: Vec3 = v3();
  37. //镜头拉近属性
  38. private _zoomDuration: number = 0.5; // 拉近持续时间(秒)
  39. private isTweening: boolean = false;
  40. onLoad(): void {
  41. this._cameraOriginalPos = this.camera.node.position.clone();
  42. this._originalRotation = this.camera.node.eulerAngles.clone();
  43. this.registerEvent();
  44. }
  45. start() {
  46. this.initilizeUI();
  47. this.saveCameraState();
  48. }
  49. private initilizeUI(){
  50. const renderNode = AliensGlobalInstance.instance.renderNode;
  51. const aimTarget = AliensGlobalInstance.instance.aimTarget;
  52. const radarNode = AliensGlobalInstance.instance.radarNode;
  53. renderNode.active = false;
  54. aimTarget.active = false;
  55. radarNode.active = false;
  56. const match = tgxUIMgr.inst.isShowing(UI_BattleGambit);
  57. if (!match) {
  58. tgxUIMgr.inst.showUI(UI_BattleGambit);
  59. }
  60. }
  61. private registerEvent(){
  62. // 触摸事件监听
  63. input.on(Input.EventType.TOUCH_START, this._onTouchStart, this);
  64. input.on(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
  65. input.on(Input.EventType.TOUCH_END, this._onTouchEnd, this);
  66. input.on(Input.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
  67. //事件监听
  68. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_AIM,this.onAimTarget,this);
  69. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_RESET_AIM,this.onResetAimTarget,this);
  70. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_SHOOT,this.onShoot,this);
  71. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_SCREENSHOT_RADAR_LOCK,this.onCameraToTarget,this);
  72. }
  73. private unRegisterEvent(){
  74. // 触摸事件监听
  75. input.off(Input.EventType.TOUCH_START, this._onTouchStart, this);
  76. input.off(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
  77. input.off(Input.EventType.TOUCH_END, this._onTouchEnd, this);
  78. input.off(Input.EventType.TOUCH_CANCEL, this._onTouchEnd, this);
  79. //事件监听
  80. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_AIM,this.onAimTarget,this);
  81. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_RESET_AIM,this.onResetAimTarget,this);
  82. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_SHOOT,this.onShoot,this);
  83. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_SCREENSHOT_RADAR_LOCK,this.onCameraToTarget,this);
  84. }
  85. private onAimTarget(){
  86. this.moveCameraAlongForward(-30); // 负值表示拉近
  87. }
  88. private onResetAimTarget(){
  89. this.moveCameraAlongForward(30); // 正值表示拉远
  90. }
  91. private onShoot(){
  92. // 获取正确的屏幕中心坐标
  93. const screenCenter = view.getVisibleSize();
  94. const screenX = screenCenter.width * 0.5 * view.getScaleX();
  95. const screenY = screenCenter.height * 0.5 * view.getScaleY();
  96. // 从屏幕中心发射射线
  97. const ray = new geometry.Ray();
  98. this.camera.screenPointToRay(screenX, screenY, ray);
  99. // 射线检测参数
  100. const mask = 0xffffffff;
  101. const maxDistance = 1000;
  102. const queryTrigger = true;
  103. // 执行射线检测
  104. const hasHit = PhysicsSystem.instance.raycast(ray, mask, maxDistance, queryTrigger);
  105. if (hasHit) {
  106. const results = PhysicsSystem.instance.raycastResults;
  107. for (let i = 0; i < results.length; i++) {
  108. const item = results[i];
  109. const hitNode = item.collider.node;
  110. // console.log(`碰撞物体${i}: ${hitNode.name} 距离: ${item.distance.toFixed(2)}`);
  111. if(hitNode.getComponent(EnemyComponent)){
  112. EventDispatcher.instance.emit(GameEvent.EVENT_CAMERA_SHOOT_TEXT);
  113. EventDispatcher.instance.emit(GameEvent.EVENT_CAMERA_SHOOT_ENEMY,hitNode);
  114. }
  115. }
  116. }
  117. }
  118. private moveCameraAlongForward(distance: number) {
  119. if(this._isZooming) return;
  120. this._isZooming = true;
  121. const currentPos = this.camera.node.position.clone();
  122. const forward = this.camera.node.forward.negative();
  123. const targetPos = currentPos.add(forward.multiplyScalar(distance));
  124. tween(this.camera.node.position)
  125. .to(this._zoomDuration, targetPos, {
  126. easing: 'smooth',
  127. onUpdate: (target: Vec3) => {
  128. this.camera.node.position = target;
  129. // 根据镜头距离动态调整旋转限制
  130. this.adjustRotationLimits();
  131. this._isZooming = false;
  132. }
  133. })
  134. .start();
  135. }
  136. //相机转向目标
  137. private async onCameraToTarget(targetNode: Node){
  138. const camera = this.camera;
  139. if (!targetNode || !camera) return;
  140. const targetPos = new Vec3();
  141. targetNode.getWorldPosition(targetPos);
  142. // 获取相机位置
  143. const cameraPos = new Vec3();
  144. camera.node.getWorldPosition(cameraPos);
  145. // 计算从相机到目标的方向向量
  146. const direction = new Vec3();
  147. Vec3.subtract(direction, targetPos, cameraPos);
  148. direction.normalize();
  149. // 计算目标欧拉角
  150. const targetYaw = math.toDegree(Math.atan2(-direction.x, -direction.z));
  151. const targetPitch = math.toDegree(Math.asin(direction.y));
  152. // 获取当前欧拉角
  153. const currentRotation = camera.node.eulerAngles.clone();
  154. // 创建一个对象用于tween
  155. const tweenObj = {
  156. pitch: currentRotation.x,
  157. yaw: currentRotation.y
  158. };
  159. this.isTweening = true;
  160. tween(tweenObj)
  161. .to(0.5, {
  162. pitch: targetPitch,
  163. yaw: targetYaw
  164. }, {
  165. easing: 'smooth',
  166. onUpdate: () => {
  167. // 更新相机旋转
  168. camera.node.setRotationFromEuler(tweenObj.pitch, tweenObj.yaw, 0);
  169. },
  170. onComplete: () => {
  171. this.isTweening = false;
  172. }
  173. })
  174. .start();
  175. }
  176. private adjustRotationLimits() {
  177. // 计算当前镜头距离比例 (0-1范围)
  178. const distanceRatio = Math.min(1, Math.max(0, (this.camera.node.position.z - this._cameraOriginalPos.z) / -30));
  179. // 动态调整旋转限制范围
  180. const dynamicMinY = this.minYRotation * (1 + distanceRatio);
  181. const dynamicMaxY = this.maxYRotation * (1 + distanceRatio);
  182. // 应用调整后的限制
  183. this.minYRotation = dynamicMinY;
  184. this.maxYRotation = dynamicMaxY;
  185. }
  186. /***************************触摸事件**********************************/
  187. private _onTouchStart(event: EventTouch) {
  188. const touchPos = event.getLocation();
  189. this._touchStartPos = v3(touchPos.x, touchPos.y, 0);
  190. this._isDragging = true;
  191. // 记录初始旋转角度
  192. this._originalRotation = this.camera.node.eulerAngles.clone();
  193. const radarComponent = AliensGlobalInstance.instance.renderNode.getComponent(RadarComponent)!;
  194. if(radarComponent){
  195. radarComponent.unlockPositionUpdate();
  196. }
  197. }
  198. private async _onTouchMove(event: EventTouch) {
  199. if (!this._isDragging) return;
  200. const currentPos = event.getLocation();
  201. const deltaX = currentPos.x - this._touchStartPos.x;
  202. const deltaY = currentPos.y - this._touchStartPos.y;
  203. // 仅计算旋转角度变化
  204. const newRotation = this._originalRotation.clone();
  205. newRotation.y = this._originalRotation.y - deltaX * 0.2;
  206. newRotation.x = this._originalRotation.x + deltaY * 0.2;
  207. // 添加旋转限制
  208. newRotation.x = Math.max(this.minXRotation, Math.min(this.maxXRotation, newRotation.x));
  209. newRotation.y = Math.max(this.minYRotation, Math.min(this.maxYRotation, newRotation.y));
  210. this.camera.node.setRotationFromEuler(newRotation);
  211. await this.saveCameraState();
  212. }
  213. //保存相机的位置和旋转角度
  214. private async saveCameraState() {
  215. const cameraOriginalPos = this.camera.node.worldPosition.clone();
  216. const originalRotation = this.camera.node.eulerAngles.clone();
  217. const screenShot = AliensGlobalInstance.instance.renderNode.getComponent(ScreenShotComponent)!;
  218. screenShot.saveCameraState(cameraOriginalPos,originalRotation);
  219. }
  220. private _onTouchEnd() {
  221. this._isDragging = false;
  222. const radarComponent = AliensGlobalInstance.instance.renderNode.getComponent(RadarComponent)!;
  223. if(radarComponent){
  224. radarComponent.unlockPositionUpdate();
  225. }
  226. }
  227. /***************************触摸事件end**********************************/
  228. onDestroy () {
  229. Tween.stopAllByTarget(this.node);
  230. this.unRegisterEvent();
  231. if (this._renderTex) {
  232. this._renderTex.destroy();
  233. this._renderTex = null;
  234. }
  235. }
  236. }