EnemyProjectileInstance.ts 16 KB

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