BallAni.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import { _decorator, Component, Node, Vec3, tween, Color,find, Sprite, resources, sp, Material } from 'cc';
  2. import EventBus, { GameEvents } from '../Core/EventBus';
  3. import { BundleLoader } from '../Core/BundleLoader';
  4. const { ccclass, property } = _decorator;
  5. /**
  6. * 小球撞击动画管理器
  7. * 负责在小球撞击时播放特效动画
  8. */
  9. @ccclass('BallAni')
  10. export class BallAni extends Component {
  11. // 撞击特效骨骼数据
  12. @property({
  13. type: sp.SkeletonData,
  14. tooltip: '拖拽撞击特效骨骼数据到这里(Animation/WeaponTx/tx0005/tx0005)'
  15. })
  16. public impactEffectSkeleton: sp.SkeletonData = null;
  17. // 白色描边材质
  18. @property({
  19. type: Material,
  20. tooltip: '拖拽白色描边材质到这里(shaders/ui-sprite-white-material)'
  21. })
  22. public whiteMaterial: Material = null;
  23. // 撞击特效预制体缓存(保持静态缓存用于性能优化)
  24. private static impactEffectSkeleton: sp.SkeletonData = null;
  25. private static isLoading: boolean = false;
  26. // 白色描边材质缓存(保持静态缓存用于性能优化)
  27. private static whiteMaterial: Material = null;
  28. private static isMaterialLoading: boolean = false;
  29. // 当前播放中的特效节点列表
  30. private activeEffects: Node[] = [];
  31. // 当前播放中的方块动画列表
  32. private activeBlockAnimations: Map<Node, any> = new Map();
  33. // 敌人生成状态
  34. private enemySpawningActive: boolean = false;
  35. start() {
  36. // 使用装饰器挂载的资源初始化静态缓存
  37. if (this.impactEffectSkeleton) {
  38. BallAni.impactEffectSkeleton = this.impactEffectSkeleton;
  39. console.log('[BallAni] ✅ 撞击特效资源通过装饰器加载成功');
  40. } else {
  41. console.warn('[BallAni] ⚠️ 撞击特效资源未设置,将使用动态加载');
  42. this.preloadImpactEffect();
  43. }
  44. if (this.whiteMaterial) {
  45. BallAni.whiteMaterial = this.whiteMaterial;
  46. console.log('[BallAni] ✅ 白色描边材质通过装饰器加载成功');
  47. } else {
  48. console.warn('[BallAni] ⚠️ 白色描边材质未设置,将使用动态加载');
  49. this.preloadWhiteMaterial();
  50. }
  51. // 监听敌人生成状态事件
  52. const eventBus = EventBus.getInstance();
  53. eventBus.on(GameEvents.ENEMY_SPAWNING_STARTED, this.onEnemySpawningStarted, this);
  54. eventBus.on(GameEvents.ENEMY_SPAWNING_STOPPED, this.onEnemySpawningStopped, this);
  55. }
  56. private onEnemySpawningStarted() {
  57. this.enemySpawningActive = true;
  58. }
  59. private onEnemySpawningStopped() {
  60. this.enemySpawningActive = false;
  61. // 当敌人生成停止时,立即检查是否需要发射子弹
  62. const eventBus = EventBus.getInstance();
  63. eventBus.emit(GameEvents.BALL_FIRE_BULLET, {
  64. canFire: (canFire: boolean) => { }
  65. });
  66. }
  67. /**
  68. * 播放方块被撞击动画
  69. * @param blockNode 方块节点
  70. */
  71. public playBlockHitAnimation(blockNode: Node) {
  72. if (!blockNode || !blockNode.isValid) {
  73. console.warn('[BallAni] 方块节点无效');
  74. return;
  75. }
  76. // 如果该方块已经在播放动画,跳过
  77. if (this.activeBlockAnimations.has(blockNode)) {
  78. console.log('[BallAni] 方块动画已在播放中,跳过');
  79. return;
  80. }
  81. // 检查是否有活跃敌人,只有有敌人时才播放缩放动画
  82. const eventBus = EventBus.getInstance();
  83. let hasActiveEnemies = false;
  84. // 通过事件系统检查是否有活跃敌人
  85. eventBus.emit(GameEvents.BALL_FIRE_BULLET, {
  86. canFire: (canFire: boolean) => {
  87. hasActiveEnemies = canFire;
  88. }
  89. });
  90. // 立即执行动画
  91. this.executeBlockAnimation(blockNode, hasActiveEnemies);
  92. // 如果敌人生成未激活,立即检查是否需要发射子弹
  93. if (!this.enemySpawningActive) {
  94. eventBus.emit(GameEvents.BALL_FIRE_BULLET, {
  95. canFire: (canFire: boolean) => { }
  96. });
  97. }
  98. }
  99. /**
  100. * 执行方块动画的具体逻辑
  101. * @param blockNode 方块节点
  102. * @param hasActiveEnemies 是否有活跃敌人
  103. */
  104. private executeBlockAnimation(blockNode: Node, hasActiveEnemies: boolean) {
  105. if (!blockNode || !blockNode.isValid) {
  106. console.warn('[BallAni] 方块节点无效');
  107. return;
  108. }
  109. // 如果该方块已经在播放动画,跳过
  110. if (this.activeBlockAnimations.has(blockNode)) {
  111. console.log('[BallAni] 方块动画已在播放中,跳过');
  112. return;
  113. }
  114. // 新的预制体结构:Sprite组件在Node子节点上
  115. const nodeChild = blockNode.getChildByName('Node');
  116. const sprite = nodeChild ? nodeChild.getComponent(Sprite) : null;
  117. // 查找预制体根节点和Weapon节点
  118. // 如果传入的是子节点(如"Node"),需要找到预制体根节点
  119. let prefabRoot = blockNode;
  120. if (blockNode.name === 'Node' && blockNode.parent) {
  121. prefabRoot = blockNode.parent;
  122. }
  123. const weaponNode = prefabRoot.getChildByName('Weapon');
  124. // 保存原始材质和缩放
  125. // 优先保存customMaterial,如果没有则保存当前material
  126. const originalMaterial = sprite ? (sprite.customMaterial || sprite.material) : null;
  127. const originalBlockScale = new Vec3(blockNode.scale.x, blockNode.scale.y, blockNode.scale.z);
  128. const originalWeaponScale = weaponNode ? new Vec3(weaponNode.scale.x, weaponNode.scale.y, weaponNode.scale.z) : null;
  129. if (hasActiveEnemies) {
  130. // 有敌人时播放方块缩放动画(包括Node和Weapon子节点)
  131. const shrinkBlockScale = new Vec3(0.8, 0.8, 1);
  132. // 应用白色描边材质到Node子节点的Sprite组件
  133. // 优先使用装饰器挂载的白色材质
  134. let whiteMaterial = null;
  135. if (this.whiteMaterial) {
  136. whiteMaterial = this.whiteMaterial;
  137. } else if (BallAni.whiteMaterial) {
  138. whiteMaterial = BallAni.whiteMaterial;
  139. }
  140. if (sprite && whiteMaterial) {
  141. sprite.material = whiteMaterial;
  142. }
  143. // 对方块预制体进行缩放动画
  144. // Weapon节点需要在其原有0.4倍基础上再进行缩放动画
  145. const weaponShrinkScale = originalWeaponScale ? new Vec3(
  146. originalWeaponScale.x * 0.8, // 在0.4倍基础上再缩小到0.8倍
  147. originalWeaponScale.y * 0.8,
  148. originalWeaponScale.z
  149. ) : null;
  150. const animationTween = tween(blockNode)
  151. .to(0.1, { scale: shrinkBlockScale }, {
  152. onStart: () => {
  153. // 开始动画时,同时缩放Weapon节点
  154. if (weaponNode && weaponShrinkScale) {
  155. tween(weaponNode)
  156. .to(0.1, { scale: weaponShrinkScale })
  157. .start();
  158. }
  159. }
  160. })
  161. .to(0.2, { scale: originalBlockScale }, {
  162. onStart: () => {
  163. // 恢复动画时,同时恢复Weapon节点
  164. if (weaponNode && originalWeaponScale) {
  165. tween(weaponNode)
  166. .to(0.2, { scale: originalWeaponScale })
  167. .start();
  168. }
  169. }
  170. })
  171. .call(() => {
  172. // 确保Weapon节点恢复到原始缩放
  173. if (weaponNode && originalWeaponScale) {
  174. weaponNode.scale = originalWeaponScale;
  175. }
  176. // 动画完成时恢复原始材质
  177. if (sprite && originalMaterial) {
  178. // 如果原始材质是customMaterial,则恢复customMaterial
  179. if (sprite.customMaterial === originalMaterial) {
  180. sprite.material = sprite.customMaterial;
  181. } else {
  182. sprite.material = originalMaterial;
  183. }
  184. } else if (sprite) {
  185. // 如果没有保存的原始材质,尝试恢复到customMaterial
  186. if (sprite.customMaterial) {
  187. sprite.material = sprite.customMaterial;
  188. } else {
  189. sprite.material = null;
  190. }
  191. }
  192. // 动画完成,从活动列表中移除
  193. this.activeBlockAnimations.delete(blockNode);
  194. })
  195. .start();
  196. // 添加到活动动画列表
  197. this.activeBlockAnimations.set(blockNode, animationTween);
  198. } else {
  199. // 没有敌人时直接结束动画,不应用材质
  200. const animationTween = tween({})
  201. .delay(0.2)
  202. .call(() => {
  203. // 动画完成,从活动列表中移除
  204. this.activeBlockAnimations.delete(blockNode);
  205. })
  206. .start();
  207. // 添加到活动动画列表
  208. this.activeBlockAnimations.set(blockNode, animationTween);
  209. }
  210. }
  211. /**
  212. * 预加载撞击特效资源
  213. */
  214. private preloadImpactEffect() {
  215. if (BallAni.impactEffectSkeleton || BallAni.isLoading) {
  216. return;
  217. }
  218. BallAni.isLoading = true;
  219. const path = 'WeaponTx/tx0005/tx0005';
  220. BundleLoader.loadSkeletonData(path).then((sData) => {
  221. BallAni.isLoading = false;
  222. if (!sData) {
  223. console.warn('[BallAni] 加载撞击特效失败: 资源为空');
  224. return;
  225. }
  226. BallAni.impactEffectSkeleton = sData;
  227. console.log('[BallAni] 撞击特效资源加载成功');
  228. }).catch((err) => {
  229. BallAni.isLoading = false;
  230. console.warn('[BallAni] 加载撞击特效失败:', err);
  231. });
  232. }
  233. /**
  234. * 预加载白色描边材质
  235. */
  236. private preloadWhiteMaterial() {
  237. if (BallAni.whiteMaterial || BallAni.isMaterialLoading) {
  238. return;
  239. }
  240. BallAni.isMaterialLoading = true;
  241. const materialPath = 'shaders/ui-sprite-white-material';
  242. resources.load(materialPath, Material, (err, material: Material) => {
  243. BallAni.isMaterialLoading = false;
  244. if (err || !material) {
  245. console.warn('[BallAni] 加载白色描边材质失败:', err);
  246. return;
  247. }
  248. BallAni.whiteMaterial = material;
  249. console.log('[BallAni] 白色描边材质加载成功');
  250. });
  251. }
  252. /**
  253. * 在指定位置播放撞击特效
  254. * @param worldPosition 世界坐标位置
  255. */
  256. public playImpactEffect(worldPosition: Vec3) {
  257. // 优先使用装饰器挂载的资源
  258. if (this.impactEffectSkeleton) {
  259. this.createAndPlayEffect(worldPosition, this.impactEffectSkeleton);
  260. return;
  261. }
  262. // 如果装饰器资源未设置,使用静态缓存
  263. if (BallAni.impactEffectSkeleton) {
  264. this.createAndPlayEffect(worldPosition, BallAni.impactEffectSkeleton);
  265. return;
  266. }
  267. // 最后才使用动态加载
  268. const path = 'WeaponTx/tx0005/tx0005';
  269. const bundleLoader = BundleLoader.getInstance();
  270. BundleLoader.loadSkeletonData(path).then((sData) => {
  271. if (!sData) {
  272. console.warn('[BallAni] 加载撞击特效失败: 资源为空');
  273. return;
  274. }
  275. BallAni.impactEffectSkeleton = sData;
  276. this.createAndPlayEffect(worldPosition, sData);
  277. }).catch((err) => {
  278. console.warn('[BallAni] 加载撞击特效失败:', err);
  279. });
  280. }
  281. /**
  282. * 创建并播放特效
  283. */
  284. private createAndPlayEffect(worldPosition: Vec3, skeletonData: sp.SkeletonData) {
  285. const effectNode = new Node('ImpactEffect');
  286. const skeleton = effectNode.addComponent(sp.Skeleton);
  287. skeleton.skeletonData = skeletonData;
  288. skeleton.premultipliedAlpha = false;
  289. skeleton.setAnimation(0, 'animation', false);
  290. skeleton.setCompleteListener(() => {
  291. this.removeEffect(effectNode);
  292. });
  293. const canvas = find('Canvas');
  294. if (canvas) {
  295. canvas.addChild(effectNode);
  296. effectNode.setWorldPosition(worldPosition);
  297. // 设置特效缩放
  298. effectNode.setScale(1.5, 1.5, 1);
  299. // 设置特效更亮 - 增加亮度
  300. const color = new Color(255, 255, 255, 255);
  301. color.r = Math.min(255, color.r * 1.5);
  302. color.g = Math.min(255, color.g * 1.5);
  303. color.b = Math.min(255, color.b * 1.5);
  304. effectNode.getComponent(sp.Skeleton).color = color;
  305. // 添加到活动特效列表
  306. this.activeEffects.push(effectNode);
  307. } else {
  308. effectNode.destroy();
  309. }
  310. }
  311. /**
  312. * 移除特效节点
  313. * @param effectNode 要移除的特效节点
  314. */
  315. private removeEffect(effectNode: Node) {
  316. // 从活动特效列表中移除
  317. const index = this.activeEffects.indexOf(effectNode);
  318. if (index !== -1) {
  319. this.activeEffects.splice(index, 1);
  320. }
  321. // 销毁节点
  322. if (effectNode && effectNode.isValid) {
  323. effectNode.destroy();
  324. }
  325. }
  326. /**
  327. * 停止指定方块的动画
  328. * @param blockNode 方块节点
  329. */
  330. public stopBlockAnimation(blockNode: Node) {
  331. const animation = this.activeBlockAnimations.get(blockNode);
  332. if (animation) {
  333. animation.stop();
  334. this.activeBlockAnimations.delete(blockNode);
  335. }
  336. }
  337. /**
  338. * 清理所有活动的特效
  339. */
  340. public clearAllEffects() {
  341. for (const effect of this.activeEffects) {
  342. if (effect && effect.isValid) {
  343. effect.destroy();
  344. }
  345. }
  346. this.activeEffects = [];
  347. }
  348. /**
  349. * 清除所有方块动画
  350. */
  351. public clearAllBlockAnimations() {
  352. // 停止所有方块动画
  353. for (const [blockNode, animation] of this.activeBlockAnimations) {
  354. if (animation) {
  355. animation.stop();
  356. }
  357. }
  358. this.activeBlockAnimations.clear();
  359. }
  360. onDestroy() {
  361. // 解绑事件监听
  362. const eventBus = EventBus.getInstance();
  363. eventBus.off(GameEvents.ENEMY_SPAWNING_STARTED, this.onEnemySpawningStarted, this);
  364. eventBus.off(GameEvents.ENEMY_SPAWNING_STOPPED, this.onEnemySpawningStopped, this);
  365. // 组件销毁时清理所有特效和动画
  366. this.clearAllEffects();
  367. this.clearAllBlockAnimations();
  368. }
  369. /**
  370. * 获取BallAni实例
  371. * @returns BallAni实例
  372. */
  373. public static getInstance(): BallAni | null {
  374. const gameArea = find('Canvas/GameLevelUI/GameArea');
  375. if (!gameArea) {
  376. console.warn('[BallAni] 未找到GameArea节点');
  377. return null;
  378. }
  379. const ballAni = gameArea.getComponent(BallAni);
  380. if (!ballAni) {
  381. console.warn('[BallAni] GameArea节点上未找到BallAni组件');
  382. return null;
  383. }
  384. return ballAni;
  385. }
  386. }