LevelAction.ts 12 KB

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