EnemyProjectileInstance.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import { _decorator, Component, Node, Vec3, RigidBody2D, Collider2D, Contact2DType, IPhysics2DContact, Sprite, find, SpriteFrame } 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. // 根据类型刷新外观(异步加载)
  80. this.setupProjectileSprite();
  81. console.log(`[EnemyProjectileInstance] 初始化抛掷物完成: 类型=${this.projectileType}, 伤害=${this.damage}, 速度=${this.speed}`);
  82. console.log('[EnemyProjectileInstance] 起始位置:', config.startPosition);
  83. }
  84. /**
  85. * 获取预制体中已配置的组件
  86. */
  87. private setupComponents() {
  88. // 获取预制体中已配置的刚体组件
  89. this.rigidBody = this.getComponent(RigidBody2D);
  90. if (!this.rigidBody) {
  91. console.error('[EnemyProjectileInstance] 预制体中未找到RigidBody2D组件');
  92. } else {
  93. console.log('[EnemyProjectileInstance] 找到RigidBody2D组件');
  94. }
  95. // 获取预制体中已配置的碰撞器组件
  96. this.collider = this.getComponent(Collider2D);
  97. if (!this.collider) {
  98. console.error('[EnemyProjectileInstance] 预制体中未找到Collider2D组件');
  99. } else {
  100. console.log('[EnemyProjectileInstance] 找到Collider2D组件');
  101. }
  102. // 获取预制体中已配置的精灵组件
  103. this.sprite = this.getComponent(Sprite);
  104. if (!this.sprite) {
  105. console.error('[EnemyProjectileInstance] 预制体中未找到Sprite组件');
  106. } else {
  107. console.log('[EnemyProjectileInstance] 找到Sprite组件');
  108. }
  109. }
  110. /**
  111. * 设置抛掷物外观:
  112. * - 法师僵尸 (magic_bolt) 使用 Animation/EnemyAni/003/ball.png
  113. * - 其它类型保持预制体默认图片
  114. */
  115. private async setupProjectileSprite() {
  116. if (!this.sprite) return;
  117. try {
  118. if (this.projectileType === 'magic_bolt') {
  119. const loader = BundleLoader.getInstance();
  120. const framePath = 'EnemyAni/003/ball/spriteFrame';
  121. const spriteFrame = await loader.loadAssetFromBundle<SpriteFrame>('Animation', framePath, SpriteFrame);
  122. if (spriteFrame && this.sprite && this.sprite.isValid) {
  123. this.sprite.spriteFrame = spriteFrame;
  124. console.log('[EnemyProjectileInstance] 已应用法师抛掷物外观: ball.png');
  125. }
  126. } else {
  127. // 保持预制体默认图片(例如弓箭手箭矢),不做修改
  128. console.log(`[EnemyProjectileInstance] 使用默认抛掷物外观,类型=${this.projectileType}`);
  129. }
  130. } catch (err) {
  131. console.error('[EnemyProjectileInstance] 加载抛掷物SpriteFrame失败', err);
  132. }
  133. }
  134. /**
  135. * 设置碰撞监听
  136. */
  137. private setupCollisionListener() {
  138. if (this.collider) {
  139. this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  140. console.log('[EnemyProjectileInstance] 碰撞监听设置完成');
  141. }
  142. }
  143. /**
  144. * 移动抛掷物
  145. */
  146. private moveProjectile(deltaTime: number) {
  147. if (!this.rigidBody) return;
  148. // 计算移动向量
  149. const moveVector = this.direction.clone().multiplyScalar(this.speed * deltaTime);
  150. // 获取当前位置并添加移动向量
  151. const currentPos = this.node.getWorldPosition();
  152. const newPos = currentPos.add(moveVector);
  153. // 设置新位置
  154. this.node.setWorldPosition(newPos);
  155. }
  156. /**
  157. * 初始化弧线弹道
  158. */
  159. private initArcTrajectory() {
  160. if (!this.useArcTrajectory) return;
  161. // 寻找最近的墙体作为目标
  162. this.findNearestWall();
  163. // 计算带45°随机偏移的初始方向
  164. const baseDir = this.direction.clone().normalize();
  165. const sign = Math.random() < 0.5 ? 1 : -1;
  166. const rad = 45 * Math.PI / 180 * sign;
  167. const cos = Math.cos(rad);
  168. const sin = Math.sin(rad);
  169. const offsetDir = new Vec3(
  170. baseDir.x * cos - baseDir.y * sin,
  171. baseDir.x * sin + baseDir.y * cos,
  172. 0
  173. ).normalize();
  174. this.arcDir = offsetDir;
  175. // 如果找到了目标墙体,设置目标方向
  176. if (this.targetWallPosition) {
  177. const currentPos = this.node.getWorldPosition();
  178. const dirToWall = this.targetWallPosition.clone().subtract(currentPos).normalize();
  179. this.arcTargetDir = dirToWall;
  180. } else {
  181. // 如果没有找到墙体,使用基础方向
  182. this.arcTargetDir = baseDir;
  183. }
  184. console.log(`[EnemyProjectileInstance] 初始化弧线弹道: 目标墙体位置=${this.targetWallPosition}`);
  185. }
  186. /**
  187. * 寻找最近的墙体
  188. */
  189. private findNearestWall() {
  190. const currentPos = this.node.getWorldPosition();
  191. let nearestWall: Node = null;
  192. let nearestDistance = Infinity;
  193. // 方法1:通过EnemyController获取墙体节点
  194. const enemyController = find('Canvas/GameLevelUI/EnemyController')?.getComponent('EnemyController') as any;
  195. if (enemyController) {
  196. const wallNodes = [];
  197. if (enemyController.topFenceNode) wallNodes.push(enemyController.topFenceNode);
  198. if (enemyController.bottomFenceNode) wallNodes.push(enemyController.bottomFenceNode);
  199. for (const wall of wallNodes) {
  200. if (wall && wall.active) {
  201. const distance = Vec3.distance(currentPos, wall.getWorldPosition());
  202. if (distance < nearestDistance) {
  203. nearestDistance = distance;
  204. nearestWall = wall;
  205. }
  206. }
  207. }
  208. }
  209. // 方法2:在GameArea中搜索墙体节点
  210. if (!nearestWall) {
  211. const gameArea = find('Canvas/GameLevelUI/GameArea');
  212. if (gameArea) {
  213. for (let i = 0; i < gameArea.children.length; i++) {
  214. const child = gameArea.children[i];
  215. if (this.isWallNode(child) && child.active) {
  216. const distance = Vec3.distance(currentPos, child.getWorldPosition());
  217. if (distance < nearestDistance) {
  218. nearestDistance = distance;
  219. nearestWall = child;
  220. }
  221. }
  222. }
  223. }
  224. }
  225. // 方法3:直接搜索常见墙体路径
  226. if (!nearestWall) {
  227. const wallPaths = [
  228. 'Canvas/GameLevelUI/GameArea/TopFence',
  229. 'Canvas/GameLevelUI/GameArea/BottomFence',
  230. 'Canvas/GameLevelUI/Wall',
  231. 'Canvas/Wall',
  232. 'Canvas/TopWall',
  233. 'Canvas/BottomWall'
  234. ];
  235. for (const path of wallPaths) {
  236. const wall = find(path);
  237. if (wall && wall.active) {
  238. const distance = Vec3.distance(currentPos, wall.getWorldPosition());
  239. if (distance < nearestDistance) {
  240. nearestDistance = distance;
  241. nearestWall = wall;
  242. }
  243. }
  244. }
  245. }
  246. // 设置目标墙体位置
  247. if (nearestWall) {
  248. this.targetWallPosition = nearestWall.getWorldPosition().clone();
  249. }
  250. }
  251. private updateArcTrajectory(deltaTime: number) {
  252. if (!this.arcDir || !this.arcTargetDir) {
  253. this.moveProjectile(deltaTime);
  254. return;
  255. }
  256. // 平滑转向到目标方向
  257. const currentDir = this.arcDir.clone();
  258. const targetDir = this.arcTargetDir.clone();
  259. // 插值计算新方向
  260. const lerpFactor = Math.min(1, this.rotateSpeed * deltaTime);
  261. const newDir = new Vec3(
  262. currentDir.x + (targetDir.x - currentDir.x) * lerpFactor,
  263. currentDir.y + (targetDir.y - currentDir.y) * lerpFactor,
  264. 0
  265. ).normalize();
  266. this.arcDir = newDir;
  267. this.direction = newDir;
  268. // 以当前方向移动
  269. this.moveProjectile(deltaTime);
  270. }
  271. private isDestroyed: boolean = false;
  272. private onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  273. if (this.isDestroyed) return;
  274. const otherNode = otherCollider.node;
  275. const otherPath = this.getNodePath(otherNode);
  276. console.log(`[EnemyProjectileInstance] 碰撞到节点: ${otherNode.name} (${otherPath})`);
  277. if (this.isWallNode(otherNode)) {
  278. // 撞到墙体
  279. this.hitWall();
  280. } else if (this.isPlayerBlock(otherNode)) {
  281. // 撞到玩家方块
  282. // TODO: 造成伤害(如果有需要)
  283. this.playHitSound();
  284. this.destroyProjectile();
  285. }
  286. }
  287. private getNodePath(node: Node): string {
  288. const names: string[] = [];
  289. let current: Node | null = node;
  290. while (current) {
  291. names.unshift(current.name);
  292. current = current.parent;
  293. }
  294. return names.join('/');
  295. }
  296. private isWallNode(node: Node): boolean {
  297. const name = node.name.toLowerCase();
  298. return name.includes('fence') || name.includes('wall');
  299. }
  300. private isPlayerBlock(node: Node): boolean {
  301. const path = this.getNodePath(node);
  302. return path.includes('WeaponBlock') || path.includes('Block');
  303. }
  304. private hitWall() {
  305. this.playHitSound();
  306. this.destroyProjectile();
  307. EventBus.getInstance().emit(GameEvents.ENEMY_DAMAGE_WALL, { damage: this.damage, source: this.node });
  308. }
  309. private playHitSound() {
  310. Audio.playEnemySound('data/弹球音效/MagicianAttack.mp3');
  311. }
  312. private destroyProjectile() {
  313. this.isDestroyed = true;
  314. if (this.node && this.node.isValid) {
  315. this.node.destroy();
  316. }
  317. }
  318. onDestroy() {
  319. // 清理逻辑,如有需要
  320. }
  321. }