EnemyProjectileInstance.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { _decorator, Component, Node, Vec3, RigidBody2D, Collider2D, Contact2DType, IPhysics2DContact, Sprite, find, SpriteFrame } from 'cc';
  2. import { EnemyAttackEffectManager, AttackEffectType } from '../EnemyAttackAni/EnemyAttackEffectManager';
  3. import { BundleLoader } from '../../Core/BundleLoader';
  4. import { Audio } from '../../AudioManager/AudioManager';
  5. import EventBus, { GameEvents } from '../../Core/EventBus';
  6. const { ccclass, property } = _decorator;
  7. /**
  8. * 敌人抛掷物实例组件
  9. * 负责处理单个抛掷物的移动、碰撞和伤害
  10. * 此组件应该挂载到抛掷物预制体上
  11. */
  12. @ccclass('EnemyProjectileInstance')
  13. export class EnemyProjectileInstance extends Component {
  14. // 抛掷物属性
  15. private damage: number = 10;
  16. private speed: number = 100;
  17. private direction: Vec3 = new Vec3(0, -1, 0); // 默认向下
  18. private projectileType: string = 'arrow';
  19. // 组件引用
  20. private rigidBody: RigidBody2D = null;
  21. private collider: Collider2D = null;
  22. private sprite: Sprite = null;
  23. // 生命周期
  24. private maxLifetime: number = 5.0; // 最大存活时间
  25. private currentLifetime: number = 0;
  26. // 弧线弹道相关属性
  27. private useArcTrajectory: boolean = true; // 是否使用弧线弹道
  28. private arcDir: Vec3 = null; // 当前方向
  29. private arcTargetDir: Vec3 = null; // 目标方向
  30. private targetWallPosition: Vec3 = null; // 目标墙体位置
  31. private rotateSpeed: number = 2.0; // 转向速度
  32. onLoad() {
  33. console.log('[EnemyProjectileInstance] 抛掷物实例组件已加载');
  34. this.setupComponents();
  35. this.setupProjectileSprite();
  36. }
  37. start() {
  38. this.setupCollisionListener();
  39. }
  40. update(deltaTime: number) {
  41. // 如果已被标记为销毁,停止更新
  42. if (this.isDestroyed) {
  43. return;
  44. }
  45. // 更新生命周期
  46. this.currentLifetime += deltaTime;
  47. if (this.currentLifetime >= this.maxLifetime) {
  48. console.log('[EnemyProjectileInstance] 抛掷物超时,自动销毁');
  49. this.isDestroyed = true;
  50. this.destroyProjectile();
  51. return;
  52. }
  53. // 根据弹道类型移动抛掷物
  54. if (this.useArcTrajectory) {
  55. this.updateArcTrajectory(deltaTime);
  56. } else {
  57. this.moveProjectile(deltaTime);
  58. }
  59. }
  60. /**
  61. * 初始化抛掷物
  62. * @param config 抛掷物配置
  63. */
  64. public init(config: {
  65. damage: number;
  66. speed: number;
  67. direction: Vec3;
  68. projectileType: string;
  69. startPosition: Vec3;
  70. }) {
  71. console.log('[EnemyProjectileInstance] 初始化抛掷物配置:', config);
  72. this.damage = config.damage;
  73. this.speed = config.speed;
  74. this.direction = config.direction.clone().normalize();
  75. this.projectileType = config.projectileType;
  76. // 注意:不在这里设置位置,因为节点还没有添加到Canvas
  77. // 位置设置由EnemyProjectile.ts在添加到Canvas后处理
  78. // 初始化弧线弹道
  79. this.initArcTrajectory();
  80. // 根据类型刷新外观(异步加载)
  81. this.setupProjectileSprite();
  82. console.log(`[EnemyProjectileInstance] 初始化抛掷物完成: 类型=${this.projectileType}, 伤害=${this.damage}, 速度=${this.speed}`);
  83. console.log('[EnemyProjectileInstance] 起始位置:', config.startPosition);
  84. }
  85. /**
  86. * 获取预制体中已配置的组件
  87. */
  88. private setupComponents() {
  89. // 获取预制体中已配置的刚体组件
  90. this.rigidBody = this.getComponent(RigidBody2D);
  91. if (!this.rigidBody) {
  92. console.error('[EnemyProjectileInstance] 预制体中未找到RigidBody2D组件');
  93. } else {
  94. console.log('[EnemyProjectileInstance] 找到RigidBody2D组件');
  95. }
  96. // 获取预制体中已配置的碰撞器组件
  97. this.collider = this.getComponent(Collider2D);
  98. if (!this.collider) {
  99. console.error('[EnemyProjectileInstance] 预制体中未找到Collider2D组件');
  100. } else {
  101. console.log('[EnemyProjectileInstance] 找到Collider2D组件');
  102. }
  103. // 获取预制体中已配置的精灵组件
  104. this.sprite = this.getComponent(Sprite);
  105. if (!this.sprite) {
  106. console.error('[EnemyProjectileInstance] 预制体中未找到Sprite组件');
  107. } else {
  108. console.log('[EnemyProjectileInstance] 找到Sprite组件');
  109. }
  110. }
  111. /**
  112. * 设置抛掷物外观:
  113. * - 法师僵尸 (magic_bolt) 使用 Animation/EnemyAni/003/ball.png
  114. * - 其它类型保持预制体默认图片
  115. */
  116. private async setupProjectileSprite() {
  117. if (!this.sprite) return;
  118. try {
  119. if (this.projectileType === 'magic_bolt') {
  120. const loader = BundleLoader.getInstance();
  121. const framePath = 'EnemyAni/003/ball/spriteFrame';
  122. const spriteFrame = await loader.loadAssetFromBundle<SpriteFrame>('Animation', framePath, SpriteFrame);
  123. if (spriteFrame && this.sprite && this.sprite.isValid) {
  124. this.sprite.spriteFrame = spriteFrame;
  125. console.log('[EnemyProjectileInstance] 已应用法师抛掷物外观: ball.png');
  126. }
  127. } else {
  128. // 保持预制体默认图片(例如弓箭手箭矢),不做修改
  129. console.log(`[EnemyProjectileInstance] 使用默认抛掷物外观,类型=${this.projectileType}`);
  130. }
  131. } catch (err) {
  132. console.error('[EnemyProjectileInstance] 加载抛掷物SpriteFrame失败', err);
  133. }
  134. }
  135. /**
  136. * 设置碰撞监听
  137. */
  138. private setupCollisionListener() {
  139. if (this.collider) {
  140. this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  141. console.log('[EnemyProjectileInstance] 碰撞监听设置完成(BEGIN_CONTACT绑定)');
  142. }
  143. }
  144. /**
  145. * 移动抛掷物
  146. */
  147. private moveProjectile(deltaTime: number) {
  148. if (!this.rigidBody) return;
  149. // 计算移动向量
  150. const moveVector = this.direction.clone().multiplyScalar(this.speed * deltaTime);
  151. // 获取当前位置并添加移动向量
  152. const currentPos = this.node.getWorldPosition();
  153. const newPos = currentPos.add(moveVector);
  154. // 设置新位置
  155. this.node.setWorldPosition(newPos);
  156. }
  157. /**
  158. * 初始化弧线弹道
  159. */
  160. private initArcTrajectory() {
  161. if (!this.useArcTrajectory) return;
  162. // 寻找最近的墙体作为目标
  163. this.findNearestWall();
  164. // 计算带45°随机偏移的初始方向
  165. const baseDir = this.direction.clone().normalize();
  166. const sign = Math.random() < 0.5 ? 1 : -1;
  167. const rad = 45 * Math.PI / 180 * sign;
  168. const cos = Math.cos(rad);
  169. const sin = Math.sin(rad);
  170. const offsetDir = new Vec3(
  171. baseDir.x * cos - baseDir.y * sin,
  172. baseDir.x * sin + baseDir.y * cos,
  173. 0
  174. ).normalize();
  175. this.arcDir = offsetDir;
  176. // 如果找到了目标墙体,设置目标方向
  177. if (this.targetWallPosition) {
  178. const currentPos = this.node.getWorldPosition();
  179. const dirToWall = this.targetWallPosition.clone().subtract(currentPos).normalize();
  180. this.arcTargetDir = dirToWall;
  181. } else {
  182. // 如果没有找到墙体,使用基础方向
  183. this.arcTargetDir = baseDir;
  184. }
  185. console.log(`[EnemyProjectileInstance] 初始化弧线弹道: 目标墙体位置=${this.targetWallPosition}`);
  186. }
  187. /**
  188. * 寻找最近的墙体
  189. */
  190. private findNearestWall() {
  191. const currentPos = this.node.getWorldPosition();
  192. let nearestWall: Node = null;
  193. let nearestDistance = Infinity;
  194. // 方法1:通过EnemyController获取墙体节点
  195. const enemyController = find('Canvas/GameLevelUI/EnemyController')?.getComponent('EnemyController') as any;
  196. if (enemyController) {
  197. const wallNodes = [];
  198. if (enemyController.topFenceNode) wallNodes.push(enemyController.topFenceNode);
  199. if (enemyController.bottomFenceNode) wallNodes.push(enemyController.bottomFenceNode);
  200. for (const wall of wallNodes) {
  201. if (wall && wall.active) {
  202. const distance = Vec3.distance(currentPos, wall.getWorldPosition());
  203. if (distance < nearestDistance) {
  204. nearestDistance = distance;
  205. nearestWall = wall;
  206. }
  207. }
  208. }
  209. }
  210. // 方法2:在GameArea中搜索墙体节点
  211. if (!nearestWall) {
  212. const gameArea = find('Canvas/GameLevelUI/GameArea');
  213. if (gameArea) {
  214. for (let i = 0; i < gameArea.children.length; i++) {
  215. const child = gameArea.children[i];
  216. if (this.isWallNode(child) && child.active) {
  217. const distance = Vec3.distance(currentPos, child.getWorldPosition());
  218. if (distance < nearestDistance) {
  219. nearestDistance = distance;
  220. nearestWall = child;
  221. }
  222. }
  223. }
  224. }
  225. }
  226. // 方法3:直接搜索常见墙体路径
  227. if (!nearestWall) {
  228. const wallPaths = [
  229. 'Canvas/GameLevelUI/GameArea/TopFence',
  230. 'Canvas/GameLevelUI/GameArea/BottomFence',
  231. 'Canvas/GameLevelUI/Wall',
  232. 'Canvas/Wall',
  233. 'Canvas/TopWall',
  234. 'Canvas/BottomWall'
  235. ];
  236. for (const path of wallPaths) {
  237. const wall = find(path);
  238. if (wall && wall.active) {
  239. const distance = Vec3.distance(currentPos, wall.getWorldPosition());
  240. if (distance < nearestDistance) {
  241. nearestDistance = distance;
  242. nearestWall = wall;
  243. }
  244. }
  245. }
  246. }
  247. // 设置目标墙体位置
  248. if (nearestWall) {
  249. this.targetWallPosition = nearestWall.getWorldPosition().clone();
  250. }
  251. }
  252. private updateArcTrajectory(deltaTime: number) {
  253. if (!this.arcDir || !this.arcTargetDir) {
  254. this.moveProjectile(deltaTime);
  255. return;
  256. }
  257. // 平滑转向到目标方向
  258. const currentDir = this.arcDir.clone();
  259. const targetDir = this.arcTargetDir.clone();
  260. // 插值计算新方向
  261. const lerpFactor = Math.min(1, this.rotateSpeed * deltaTime);
  262. const newDir = new Vec3(
  263. currentDir.x + (targetDir.x - currentDir.x) * lerpFactor,
  264. currentDir.y + (targetDir.y - currentDir.y) * lerpFactor,
  265. 0
  266. ).normalize();
  267. this.arcDir = newDir;
  268. this.direction = newDir;
  269. // 以当前方向移动
  270. this.moveProjectile(deltaTime);
  271. }
  272. private isDestroyed: boolean = false;
  273. private onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  274. if (this.isDestroyed) return;
  275. const otherNode = otherCollider.node;
  276. const otherPath = this.getNodePath(otherNode);
  277. console.log(`[EnemyProjectileInstance] BEGIN_CONTACT -> 节点: ${otherNode.name} (${otherPath}), 有接触信息: ${!!contact}`);
  278. if (this.isWallNode(otherNode)) {
  279. // 撞到墙体
  280. this.hitWall(contact);
  281. } else if (this.isPlayerBlock(otherNode)) {
  282. // 撞到玩家方块
  283. // TODO: 造成伤害(如果有需要)
  284. this.playHitSound();
  285. this.destroyProjectile();
  286. }
  287. }
  288. private getNodePath(node: Node): string {
  289. const names: string[] = [];
  290. let current: Node | null = node;
  291. while (current) {
  292. names.unshift(current.name);
  293. current = current.parent;
  294. }
  295. return names.join('/');
  296. }
  297. private isWallNode(node: Node): boolean {
  298. const name = node.name.toLowerCase();
  299. return name.includes('fence') || name.includes('wall');
  300. }
  301. private isPlayerBlock(node: Node): boolean {
  302. const path = this.getNodePath(node);
  303. return path.includes('WeaponBlock') || path.includes('Block');
  304. }
  305. private hitWall(contact?: IPhysics2DContact | null) {
  306. // 计算命中位置(优先采用物理接触点)
  307. const impactPos = this.getImpactWorldPosition(contact);
  308. this.spawnWallImpactEffect(impactPos);
  309. this.playHitSound();
  310. this.destroyProjectile();
  311. EventBus.getInstance().emit(GameEvents.ENEMY_DAMAGE_WALL, { damage: this.damage, source: this.node });
  312. }
  313. private getImpactWorldPosition(contact?: IPhysics2DContact | null): Vec3 {
  314. try {
  315. const c: any = contact;
  316. if (c && typeof c.getWorldManifold === 'function') {
  317. const manifold = c.getWorldManifold();
  318. if (manifold && manifold.points && manifold.points.length > 0) {
  319. const p = manifold.points[0];
  320. const pos = new Vec3(p.x, p.y, 0);
  321. console.log(`[EnemyProjectileInstance] 使用接触点作为命中位置: (${pos.x.toFixed(1)}, ${pos.y.toFixed(1)})`);
  322. return pos;
  323. }
  324. }
  325. } catch (e) {
  326. // 忽略异常,使用抛掷物当前位置
  327. console.warn('[EnemyProjectileInstance] 接触点解析异常,回退为抛掷物当前位置');
  328. }
  329. const backup = this.node.getWorldPosition().clone();
  330. console.log(`[EnemyProjectileInstance] 使用抛掷物当前位置作为命中位置: (${backup.x.toFixed(1)}, ${backup.y.toFixed(1)})`);
  331. return backup;
  332. }
  333. private spawnWallImpactEffect(worldPos: Vec3) {
  334. const mgr = EnemyAttackEffectManager.instance;
  335. const type = this.getImpactEffectType();
  336. if (!mgr || !type) return;
  337. console.log(`[EnemyProjectileInstance] 触发墙体命中特效: type=${type}, 位置=(${worldPos.x.toFixed(1)}, ${worldPos.y.toFixed(1)})`);
  338. mgr.playImpactEffect(type, worldPos);
  339. }
  340. private getImpactEffectType(): AttackEffectType | null {
  341. const t = (this.projectileType || '').toLowerCase();
  342. console.log(`[EnemyProjectileInstance] 解析特效类型,projectileType=${this.projectileType}`);
  343. if (t === 'magic_bolt' || t.includes('magic')) {
  344. return AttackEffectType.Mage;
  345. }
  346. if (t === 'arrow' || t.includes('arrow')) {
  347. return AttackEffectType.Archer;
  348. }
  349. return null;
  350. }
  351. private playHitSound() {
  352. console.log('[EnemyProjectileInstance] 播放命中音效: data/弹球音效/MagicianAttack.mp3');
  353. Audio.playEnemySound('data/弹球音效/MagicianAttack.mp3');
  354. }
  355. private destroyProjectile() {
  356. this.isDestroyed = true;
  357. if (this.node && this.node.isValid) {
  358. console.log('[EnemyProjectileInstance] 抛掷物节点销毁');
  359. this.node.destroy();
  360. }
  361. }
  362. onDestroy() {
  363. // 清理逻辑,如有需要
  364. }
  365. }