EnemyProjectileInstance.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import { _decorator, Component, Node, Vec3, RigidBody2D, Collider2D, Contact2DType, IPhysics2DContact, Sprite, find } from 'cc';
  2. import { BundleLoader } from '../../Core/BundleLoader';
  3. import { Audio } from '../../AudioManager/AudioManager';
  4. import EventBus, { GameEvents } from '../../Core/EventBus';
  5. const { ccclass, property } = _decorator;
  6. /**
  7. * 敌人抛掷物实例组件
  8. * 负责处理单个抛掷物的移动、碰撞和伤害
  9. * 此组件应该挂载到抛掷物预制体上
  10. */
  11. @ccclass('EnemyProjectileInstance')
  12. export class EnemyProjectileInstance extends Component {
  13. // 抛掷物属性
  14. private damage: number = 10;
  15. private speed: number = 100;
  16. private direction: Vec3 = new Vec3(0, -1, 0); // 默认向下
  17. private projectileType: string = 'arrow';
  18. // 组件引用
  19. private rigidBody: RigidBody2D = null;
  20. private collider: Collider2D = null;
  21. private sprite: Sprite = null;
  22. // 生命周期
  23. private maxLifetime: number = 5.0; // 最大存活时间
  24. private currentLifetime: number = 0;
  25. // 弧线弹道相关属性
  26. private useArcTrajectory: boolean = true; // 是否使用弧线弹道
  27. private arcDir: Vec3 = null; // 当前方向
  28. private arcTargetDir: Vec3 = null; // 目标方向
  29. private targetWallPosition: Vec3 = null; // 目标墙体位置
  30. private rotateSpeed: number = 2.0; // 转向速度
  31. onLoad() {
  32. console.log('[EnemyProjectileInstance] 抛掷物实例组件已加载');
  33. this.setupComponents();
  34. this.setupProjectileSprite();
  35. }
  36. start() {
  37. this.setupCollisionListener();
  38. }
  39. update(deltaTime: number) {
  40. // 如果已被标记为销毁,停止更新
  41. if (this.isDestroyed) {
  42. return;
  43. }
  44. // 更新生命周期
  45. this.currentLifetime += deltaTime;
  46. if (this.currentLifetime >= this.maxLifetime) {
  47. console.log('[EnemyProjectileInstance] 抛掷物超时,自动销毁');
  48. this.isDestroyed = true;
  49. this.destroyProjectile();
  50. return;
  51. }
  52. // 根据弹道类型移动抛掷物
  53. if (this.useArcTrajectory) {
  54. this.updateArcTrajectory(deltaTime);
  55. } else {
  56. this.moveProjectile(deltaTime);
  57. }
  58. }
  59. /**
  60. * 初始化抛掷物
  61. * @param config 抛掷物配置
  62. */
  63. public init(config: {
  64. damage: number;
  65. speed: number;
  66. direction: Vec3;
  67. projectileType: string;
  68. startPosition: Vec3;
  69. }) {
  70. console.log('[EnemyProjectileInstance] 初始化抛掷物配置:', config);
  71. this.damage = config.damage;
  72. this.speed = config.speed;
  73. this.direction = config.direction.clone().normalize();
  74. this.projectileType = config.projectileType;
  75. // 注意:不在这里设置位置,因为节点还没有添加到Canvas
  76. // 位置设置由EnemyProjectile.ts在添加到Canvas后处理
  77. // 初始化弧线弹道
  78. this.initArcTrajectory();
  79. console.log(`[EnemyProjectileInstance] 初始化抛掷物完成: 类型=${this.projectileType}, 伤害=${this.damage}, 速度=${this.speed}`);
  80. console.log('[EnemyProjectileInstance] 起始位置:', config.startPosition);
  81. }
  82. /**
  83. * 获取预制体中已配置的组件
  84. */
  85. private setupComponents() {
  86. // 获取预制体中已配置的刚体组件
  87. this.rigidBody = this.getComponent(RigidBody2D);
  88. if (!this.rigidBody) {
  89. console.error('[EnemyProjectileInstance] 预制体中未找到RigidBody2D组件');
  90. } else {
  91. console.log('[EnemyProjectileInstance] 找到RigidBody2D组件');
  92. }
  93. // 获取预制体中已配置的碰撞器组件
  94. this.collider = this.getComponent(Collider2D);
  95. if (!this.collider) {
  96. console.error('[EnemyProjectileInstance] 预制体中未找到Collider2D组件');
  97. } else {
  98. console.log('[EnemyProjectileInstance] 找到Collider2D组件');
  99. }
  100. // 获取预制体中已配置的精灵组件
  101. this.sprite = this.getComponent(Sprite);
  102. if (!this.sprite) {
  103. console.error('[EnemyProjectileInstance] 预制体中未找到Sprite组件');
  104. } else {
  105. console.log('[EnemyProjectileInstance] 找到Sprite组件');
  106. }
  107. }
  108. /**
  109. * 设置抛掷物外观,使用3.png
  110. */
  111. private async setupProjectileSprite() {
  112. if (!this.sprite) return;
  113. }
  114. /**
  115. * 设置碰撞监听
  116. */
  117. private setupCollisionListener() {
  118. if (this.collider) {
  119. this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  120. console.log('[EnemyProjectileInstance] 碰撞监听设置完成');
  121. }
  122. }
  123. /**
  124. * 移动抛掷物
  125. */
  126. private moveProjectile(deltaTime: number) {
  127. if (!this.rigidBody) return;
  128. // 计算移动向量
  129. const moveVector = this.direction.clone().multiplyScalar(this.speed * deltaTime);
  130. // 获取当前位置并添加移动向量
  131. const currentPos = this.node.getWorldPosition();
  132. const newPos = currentPos.add(moveVector);
  133. // 设置新位置
  134. this.node.setWorldPosition(newPos);
  135. }
  136. /**
  137. * 初始化弧线弹道
  138. */
  139. private initArcTrajectory() {
  140. if (!this.useArcTrajectory) return;
  141. // 寻找最近的墙体作为目标
  142. this.findNearestWall();
  143. // 计算带45°随机偏移的初始方向
  144. const baseDir = this.direction.clone().normalize();
  145. const sign = Math.random() < 0.5 ? 1 : -1;
  146. const rad = 45 * Math.PI / 180 * sign;
  147. const cos = Math.cos(rad);
  148. const sin = Math.sin(rad);
  149. const offsetDir = new Vec3(
  150. baseDir.x * cos - baseDir.y * sin,
  151. baseDir.x * sin + baseDir.y * cos,
  152. 0
  153. ).normalize();
  154. this.arcDir = offsetDir;
  155. // 如果找到了目标墙体,设置目标方向
  156. if (this.targetWallPosition) {
  157. const currentPos = this.node.getWorldPosition();
  158. const dirToWall = this.targetWallPosition.clone().subtract(currentPos).normalize();
  159. this.arcTargetDir = dirToWall;
  160. } else {
  161. // 如果没有找到墙体,使用基础方向
  162. this.arcTargetDir = baseDir;
  163. }
  164. console.log(`[EnemyProjectileInstance] 初始化弧线弹道: 目标墙体位置=${this.targetWallPosition}`);
  165. }
  166. /**
  167. * 寻找最近的墙体
  168. */
  169. private findNearestWall() {
  170. const currentPos = this.node.getWorldPosition();
  171. let nearestWall: Node = null;
  172. let nearestDistance = Infinity;
  173. // 方法1:通过EnemyController获取墙体节点
  174. const enemyController = find('Canvas/GameLevelUI/EnemyController')?.getComponent('EnemyController') as any;
  175. if (enemyController) {
  176. const wallNodes = [];
  177. if (enemyController.topFenceNode) wallNodes.push(enemyController.topFenceNode);
  178. if (enemyController.bottomFenceNode) wallNodes.push(enemyController.bottomFenceNode);
  179. for (const wall of wallNodes) {
  180. if (wall && wall.active) {
  181. const distance = Vec3.distance(currentPos, wall.getWorldPosition());
  182. if (distance < nearestDistance) {
  183. nearestDistance = distance;
  184. nearestWall = wall;
  185. }
  186. }
  187. }
  188. }
  189. // 方法2:在GameArea中搜索墙体节点
  190. if (!nearestWall) {
  191. const gameArea = find('Canvas/GameLevelUI/GameArea');
  192. if (gameArea) {
  193. for (let i = 0; i < gameArea.children.length; i++) {
  194. const child = gameArea.children[i];
  195. if (this.isWallNode(child) && child.active) {
  196. const distance = Vec3.distance(currentPos, child.getWorldPosition());
  197. if (distance < nearestDistance) {
  198. nearestDistance = distance;
  199. nearestWall = child;
  200. }
  201. }
  202. }
  203. }
  204. }
  205. // 方法3:直接搜索常见墙体路径
  206. if (!nearestWall) {
  207. const wallPaths = [
  208. 'Canvas/GameLevelUI/GameArea/TopFence',
  209. 'Canvas/GameLevelUI/GameArea/BottomFence',
  210. 'Canvas/GameLevelUI/Wall',
  211. 'Canvas/Wall',
  212. 'Canvas/TopWall',
  213. 'Canvas/BottomWall'
  214. ];
  215. for (const path of wallPaths) {
  216. const wall = find(path);
  217. if (wall && wall.active) {
  218. const distance = Vec3.distance(currentPos, wall.getWorldPosition());
  219. if (distance < nearestDistance) {
  220. nearestDistance = distance;
  221. nearestWall = wall;
  222. }
  223. }
  224. }
  225. }
  226. if (nearestWall) {
  227. this.targetWallPosition = nearestWall.getWorldPosition();
  228. console.log(`[EnemyProjectileInstance] 找到目标墙体: ${nearestWall.name}, 距离: ${nearestDistance.toFixed(2)}`);
  229. } else {
  230. console.warn('[EnemyProjectileInstance] 未找到可用的墙体目标');
  231. // 设置一个默认的目标位置(屏幕中心下方)
  232. this.targetWallPosition = new Vec3(0, -200, 0);
  233. }
  234. }
  235. /**
  236. * 更新弧线弹道
  237. */
  238. private updateArcTrajectory(deltaTime: number) {
  239. if (!this.arcDir || !this.arcTargetDir) return;
  240. // 重新寻找墙体目标(动态追踪)
  241. if (!this.targetWallPosition) {
  242. this.findNearestWall();
  243. }
  244. // 更新目标方向
  245. if (this.targetWallPosition) {
  246. const currentPos = this.node.getWorldPosition();
  247. const dirToWall = this.targetWallPosition.clone().subtract(currentPos).normalize();
  248. this.arcTargetDir.set(dirToWall);
  249. }
  250. // 计算转向
  251. const rotateFactor = this.rotateSpeed * deltaTime;
  252. this.arcDir = this.arcDir.lerp(this.arcTargetDir, rotateFactor).normalize();
  253. // 计算移动向量
  254. const moveVector = this.arcDir.clone().multiplyScalar(this.speed * deltaTime);
  255. // 获取当前位置并添加移动向量
  256. const currentPos = this.node.getWorldPosition();
  257. const newPos = currentPos.add(moveVector);
  258. // 设置新位置
  259. this.node.setWorldPosition(newPos);
  260. // 更新节点朝向(可选)
  261. const angle = Math.atan2(this.arcDir.y, this.arcDir.x) * 180 / Math.PI;
  262. this.node.angle = angle;
  263. }
  264. // 防止重复销毁的标志
  265. private isDestroyed: boolean = false;
  266. /**
  267. * 碰撞开始事件
  268. */
  269. private onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  270. // 如果已经被销毁,不再处理碰撞
  271. if (this.isDestroyed) {
  272. console.log(`[EnemyProjectileInstance] 抛掷物已被销毁,忽略碰撞事件`);
  273. return;
  274. }
  275. const otherNode = otherCollider.node;
  276. const nodeName = otherNode.name;
  277. console.log(`[EnemyProjectileInstance] 抛掷物碰撞检测 - 碰撞对象: ${nodeName}, 节点路径: ${this.getNodePath(otherNode)}`);
  278. // 抛掷物的目标是墙体,检查是否碰到墙体
  279. if (this.isWallNode(otherNode)) {
  280. console.log(`[EnemyProjectileInstance] 抛掷物击中目标墙体: ${nodeName}, 准备销毁`);
  281. this.hitWall();
  282. return;
  283. }
  284. console.log(`[EnemyProjectileInstance] 抛掷物碰撞到非目标对象: ${nodeName}, 继续飞行`);
  285. }
  286. /**
  287. * 获取节点的完整路径
  288. */
  289. private getNodePath(node: Node): string {
  290. const path = [];
  291. let current = node;
  292. while (current) {
  293. path.unshift(current.name);
  294. current = current.parent;
  295. }
  296. return path.join('/');
  297. }
  298. /**
  299. * 检查是否为墙体节点
  300. */
  301. private isWallNode(node: Node): boolean {
  302. const nodeName = node.name.toLowerCase();
  303. // 检查节点名称是否包含墙体关键词
  304. const wallKeywords = ['wall', 'fence', 'jiguang', '墙', '围栏'];
  305. const isWallByName = wallKeywords.some(keyword => nodeName.includes(keyword));
  306. // 检查节点是否有Wall组件
  307. const hasWallComponent = node.getComponent('Wall') !== null;
  308. return isWallByName || hasWallComponent;
  309. }
  310. /**
  311. * 检查是否为玩家方块
  312. */
  313. private isPlayerBlock(node: Node): boolean {
  314. // 检查节点名称或标签
  315. return node.name.includes('Block') || node.name.includes('WeaponBlock');
  316. }
  317. /**
  318. * 击中墙体
  319. */
  320. private hitWall() {
  321. // 防止重复销毁
  322. if (this.isDestroyed) {
  323. console.log(`[EnemyProjectileInstance] 抛掷物已被销毁,忽略hitWall调用`);
  324. return;
  325. }
  326. this.isDestroyed = true;
  327. console.log(`[EnemyProjectileInstance] 抛掷物击中墙体,造成 ${this.damage} 点伤害,开始销毁流程`);
  328. // 对墙体造成伤害
  329. EventBus.getInstance().emit(GameEvents.ENEMY_DAMAGE_WALL, {
  330. damage: this.damage,
  331. source: this.node
  332. });
  333. // 播放击中音效
  334. this.playHitSound();
  335. // 销毁抛掷物
  336. this.destroyProjectile();
  337. }
  338. /**
  339. * 击中玩家方块(已移除,抛掷物不攻击玩家方块)
  340. */
  341. /*
  342. private hitPlayerBlock(blockNode: Node) {
  343. // 防止重复销毁
  344. if (this.isDestroyed) {
  345. console.log(`[EnemyProjectileInstance] 抛掷物已被销毁,忽略hitPlayerBlock调用`);
  346. return;
  347. }
  348. this.isDestroyed = true;
  349. console.log(`[EnemyProjectileInstance] 抛掷物击中玩家方块: ${blockNode.name},开始销毁流程`);
  350. // 对玩家方块造成伤害 - 使用事件系统
  351. EventBus.getInstance().emit(GameEvents.ENEMY_DAMAGE_PLAYER_BLOCK, {
  352. damage: this.damage,
  353. blockNode: blockNode,
  354. source: this.node
  355. });
  356. // 播放击中音效
  357. this.playHitSound();
  358. // 销毁抛掷物
  359. this.destroyProjectile();
  360. }
  361. */
  362. /**
  363. * 播放击中音效
  364. */
  365. private playHitSound() {
  366. // 根据抛掷物类型播放不同音效
  367. let soundPath = '';
  368. switch (this.projectileType) {
  369. case 'arrow':
  370. soundPath = 'data/弹球音效/fire';
  371. break;
  372. case 'magic_bolt':
  373. soundPath = 'data/弹球音效/fire';
  374. break;
  375. default:
  376. soundPath = 'data/弹球音效/fire';
  377. break;
  378. }
  379. if (soundPath) {
  380. Audio.playWeaponSound(soundPath);
  381. }
  382. }
  383. /**
  384. * 销毁抛掷物
  385. */
  386. private destroyProjectile() {
  387. // 防止重复销毁
  388. if (this.isDestroyed && (!this.node || !this.node.isValid)) {
  389. console.log('[EnemyProjectileInstance] 抛掷物已被销毁,跳过重复销毁');
  390. return;
  391. }
  392. if (this.node && this.node.isValid) {
  393. console.log('[EnemyProjectileInstance] 销毁抛掷物节点');
  394. this.node.destroy();
  395. } else {
  396. console.log('[EnemyProjectileInstance] 抛掷物节点已无效或不存在');
  397. }
  398. }
  399. onDestroy() {
  400. // 清理碰撞监听
  401. if (this.collider) {
  402. this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  403. }
  404. console.log('[EnemyProjectileInstance] 抛掷物实例组件已销毁');
  405. }
  406. }