HPBarAnimation.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import { _decorator, Component, Node, ProgressBar, tween, UITransform, Vec3, BoxCollider2D, Collider2D, CircleCollider2D } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. /**
  4. * 血条动画组件
  5. * 使用两个重叠的血条实现黄色血皮滑动动画效果
  6. * 红色血条显示当前血量,黄色血条用于滑动动画
  7. * 血条默认隐藏,只在受伤时显示并播放动画
  8. */
  9. @ccclass('HPBarAnimation')
  10. export class HPBarAnimation extends Component {
  11. @property({
  12. type: Node,
  13. tooltip: '红色血条节点'
  14. })
  15. public redBarNode: Node = null;
  16. @property({
  17. type: Node,
  18. tooltip: '黄色血条节点'
  19. })
  20. public yellowBarNode: Node = null;
  21. @property({
  22. type: Node,
  23. tooltip: 'HPBar根节点'
  24. })
  25. public hpBarRootNode: Node = null;
  26. @property({ tooltip: '血条相对敌人顶部的额外偏移(像素)' })
  27. public offsetY: number = 18;
  28. @property({ tooltip: '优先使用碰撞体高度定位' })
  29. public useColliderForTop: boolean = true;
  30. @property({ tooltip: '打印调试日志' })
  31. public debugLogs: boolean = true;
  32. private redProgressBar: ProgressBar = null;
  33. private yellowProgressBar: ProgressBar = null;
  34. private currentProgress: number = 1.0;
  35. private targetProgress: number = 1.0;
  36. private currentTween: any = null; // 当前正在运行的动画
  37. private hideTimer: any = null; // 隐藏血条的定时器
  38. start() {
  39. this.initializeComponents();
  40. this.updateBarPosition(true);
  41. if (this.debugLogs) console.log(`[HPBarAnimation] start: node=${this.getNodePath(this.node)}`);
  42. }
  43. /**
  44. * 初始化组件
  45. */
  46. private initializeComponents() {
  47. // 获取组件所属的敌人节点信息
  48. const enemyNode = this.node;
  49. const enemyName = enemyNode ? enemyNode.name : 'Unknown';
  50. if (this.debugLogs) console.log(`[HPBarAnimation] initialize on ${this.getNodePath(this.node)} enemy=${enemyName}`);
  51. // 如果没有设置HPBar根节点,尝试自动查找或使用当前节点
  52. if (!this.hpBarRootNode) {
  53. const child = this.node.getChildByName('HPBar');
  54. if (child) {
  55. this.hpBarRootNode = child;
  56. if (this.debugLogs) console.log(`[HPBarAnimation] 自动设置 hpBarRootNode 为子节点: ${this.getNodePath(child)}`);
  57. } else {
  58. this.hpBarRootNode = this.node;
  59. if (this.debugLogs) console.log(`[HPBarAnimation] 未找到子节点 HPBar,hpBarRootNode 使用当前节点: ${this.getNodePath(this.node)}`);
  60. }
  61. }
  62. // 获取红色血条组件
  63. if (this.redBarNode) {
  64. this.redProgressBar = this.redBarNode.getComponent(ProgressBar);
  65. if (this.redProgressBar) {
  66. this.currentProgress = this.redProgressBar.progress;
  67. this.targetProgress = this.currentProgress;
  68. } else {
  69. console.error(`[HPBarAnimation] [${enemyName}] 红色血条节点上未找到ProgressBar组件!`);
  70. }
  71. } else {
  72. console.error(`[HPBarAnimation] [${enemyName}] 红色血条节点未设置!`);
  73. }
  74. // 获取黄色血条组件
  75. if (this.yellowBarNode) {
  76. this.yellowProgressBar = this.yellowBarNode.getComponent(ProgressBar);
  77. if (this.yellowProgressBar) {
  78. // 黄色血条初始进度与红色血条同步
  79. this.yellowProgressBar.progress = this.currentProgress;
  80. } else {
  81. console.error(`[HPBarAnimation] [${enemyName}] 黄色血条节点上未找到ProgressBar组件!`);
  82. }
  83. } else {
  84. console.error(`[HPBarAnimation] [${enemyName}] 黄色血条节点未设置!`);
  85. }
  86. // 初始化时隐藏血条
  87. this.hideHealthBar();
  88. }
  89. /**
  90. * 获取节点路径
  91. */
  92. private getNodePath(node: Node): string {
  93. if (!node) return 'null';
  94. let path = node.name;
  95. let current = node;
  96. while (current.parent) {
  97. current = current.parent;
  98. path = current.name + '/' + path;
  99. }
  100. return path;
  101. }
  102. /**
  103. * 更新血条显示
  104. */
  105. private updateBarDisplay() {
  106. if (!this.redProgressBar || !this.yellowProgressBar) {
  107. return;
  108. }
  109. // 红色血条显示当前血量
  110. if (this.redProgressBar && this.redProgressBar.isValid) {
  111. this.redProgressBar.progress = this.currentProgress;
  112. }
  113. }
  114. /**
  115. * 显示血条
  116. */
  117. public showHealthBar() {
  118. // 仅在首次显示时进行定位计算,避免每次受击重复计算
  119. const barNode = (this.hpBarRootNode && this.hpBarRootNode.isValid) ? this.hpBarRootNode : this.node;
  120. const wasActive = barNode.active;
  121. if (!wasActive) {
  122. this.updateBarPosition();
  123. }
  124. if (this.hpBarRootNode && this.hpBarRootNode.isValid) {
  125. this.hpBarRootNode.active = true;
  126. if (this.debugLogs) console.log(`[HPBarAnimation] showHealthBar: active=true path=${this.getNodePath(this.hpBarRootNode)}`);
  127. } else {
  128. if (this.debugLogs) console.warn(`[HPBarAnimation] showHealthBar: hpBarRootNode 无效,使用当前节点 path=${this.getNodePath(this.node)}`);
  129. this.node.active = true;
  130. }
  131. // 清除隐藏定时器
  132. if (this.hideTimer) {
  133. clearTimeout(this.hideTimer);
  134. this.hideTimer = null;
  135. }
  136. }
  137. /**
  138. * 隐藏血条
  139. */
  140. public hideHealthBar() {
  141. if (this.hpBarRootNode && this.hpBarRootNode.isValid) {
  142. this.hpBarRootNode.active = false;
  143. if (this.debugLogs) console.log(`[HPBarAnimation] hideHealthBar: active=false path=${this.getNodePath(this.hpBarRootNode)}`);
  144. } else {
  145. if (this.debugLogs) console.warn(`[HPBarAnimation] hideHealthBar: hpBarRootNode 无效,使用当前节点 path=${this.getNodePath(this.node)}`);
  146. this.node.active = false;
  147. }
  148. }
  149. /**
  150. * 延迟隐藏血条
  151. * @param delay 延迟时间(秒)
  152. */
  153. private scheduleHideHealthBar(delay: number = 3.0) {
  154. if (this.debugLogs) console.log(`[HPBarAnimation] scheduleHideHealthBar: delay=${delay}s path=${this.getNodePath(this.hpBarRootNode || this.node)}`);
  155. // 清除之前的定时器
  156. if (this.hideTimer) {
  157. clearTimeout(this.hideTimer);
  158. }
  159. // 设置新的定时器
  160. this.hideTimer = setTimeout(() => {
  161. this.hideHealthBar();
  162. this.hideTimer = null;
  163. }, delay * 1000);
  164. }
  165. /**
  166. * 更新血条进度并播放动画
  167. * @param newProgress 新的血量百分比 (0-1)
  168. * @param showBar 是否显示血条(默认为true)
  169. */
  170. public updateProgress(newProgress: number, showBar: boolean = true) {
  171. const enemyName = this.node ? this.node.name : 'Unknown';
  172. if (this.debugLogs) console.log(`[HPBarAnimation] updateProgress(showBar=${showBar}) ${this.currentProgress} -> ${newProgress}`);
  173. if (!this.redProgressBar || !this.yellowProgressBar) {
  174. console.warn(`[HPBarAnimation] [${enemyName}] 红色或黄色血条组件未初始化`);
  175. return;
  176. }
  177. newProgress = Math.max(0, Math.min(1, newProgress));
  178. if (showBar) {
  179. this.showHealthBar();
  180. // 定位仅在首次显示时执行,避免受击重复计算
  181. }
  182. // 如果血量增加或没有变化,直接更新
  183. if (newProgress >= this.currentProgress) {
  184. this.currentProgress = newProgress;
  185. this.targetProgress = newProgress;
  186. // 同步更新两个血条
  187. if (this.redProgressBar && this.redProgressBar.isValid) {
  188. this.redProgressBar.progress = newProgress;
  189. }
  190. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  191. this.yellowProgressBar.progress = newProgress;
  192. }
  193. this.updateBarDisplay();
  194. // 如果血量满了,立即隐藏血条
  195. if (newProgress >= 1.0) {
  196. this.scheduleHideHealthBar(1.0); // 1秒后隐藏
  197. } else if (showBar) {
  198. this.scheduleHideHealthBar(3.0); // 3秒后隐藏
  199. }
  200. return;
  201. }
  202. // 血量减少时播放黄色血皮滑动动画
  203. this.playDamageAnimation(newProgress);
  204. }
  205. /**
  206. * 播放伤害动画
  207. * @param newProgress 新的血量百分比
  208. */
  209. private playDamageAnimation(newProgress: number) {
  210. console.log(`[HPBarAnimation] 开始播放伤害动画:${this.currentProgress} -> ${newProgress}`);
  211. // 停止当前正在运行的动画,避免动画冲突
  212. if (this.currentTween) {
  213. this.currentTween.stop();
  214. this.currentTween = null;
  215. }
  216. this.targetProgress = newProgress;
  217. // 保存原始血量作为黄色血条起始位置
  218. const originalProgress = this.currentProgress;
  219. // 1. 立即更新红色血条到新的血量值
  220. this.currentProgress = newProgress;
  221. if (this.redProgressBar && this.redProgressBar.isValid) {
  222. this.redProgressBar.progress = newProgress;
  223. }
  224. // 2. 黄色血条从原血量滑动到新血量位置
  225. // 黄色血条保持在原始位置
  226. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  227. this.yellowProgressBar.progress = originalProgress;
  228. }
  229. this.updateBarDisplay();
  230. // 创建滑动动画,先暂停0.4秒再滑动
  231. this.currentTween = tween({ progress: originalProgress })
  232. .delay(0.4) // 暂停0.4秒
  233. .to(0.3, { progress: newProgress }, {
  234. onUpdate: (target) => {
  235. // 动画过程中更新黄色血条进度
  236. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  237. this.yellowProgressBar.progress = target.progress;
  238. this.updateBarDisplay();
  239. }
  240. },
  241. onComplete: () => {
  242. // 动画完成后黄色血条进度等于当前血量
  243. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  244. this.yellowProgressBar.progress = newProgress;
  245. this.updateBarDisplay();
  246. }
  247. // 清除动画引用
  248. this.currentTween = null;
  249. // 动画完成后延迟隐藏血条
  250. if (newProgress > 0) {
  251. this.scheduleHideHealthBar(3.0); // 3秒后隐藏血条
  252. }
  253. }
  254. })
  255. .start();
  256. }
  257. /**
  258. * 获取当前血量百分比
  259. */
  260. public getCurrentProgress(): number {
  261. return this.currentProgress;
  262. }
  263. /**
  264. * 重置血条到满血状态
  265. */
  266. public resetToFull() {
  267. this.updateProgress(1.0, false); // 重置时不显示血条
  268. }
  269. /**
  270. * 重置血条到满血状态并隐藏
  271. */
  272. public resetToFullAndHide() {
  273. this.currentProgress = 1.0;
  274. this.targetProgress = 1.0;
  275. // 同步更新两个血条到满血状态
  276. if (this.redProgressBar && this.redProgressBar.isValid) {
  277. this.redProgressBar.progress = 1.0;
  278. }
  279. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  280. this.yellowProgressBar.progress = 1.0;
  281. }
  282. this.updateBarDisplay();
  283. // 立即隐藏血条
  284. this.hideHealthBar();
  285. }
  286. onDestroy() {
  287. // 清理正在运行的动画,防止内存泄漏
  288. if (this.currentTween) {
  289. this.currentTween.stop();
  290. this.currentTween = null;
  291. }
  292. // 清理隐藏血条的定时器,防止内存泄漏
  293. if (this.hideTimer) {
  294. clearTimeout(this.hideTimer);
  295. this.hideTimer = null;
  296. }
  297. }
  298. public updateBarPosition(force: boolean = false) {
  299. // 以血条节点作为基准(兼容脚本挂在 Enemy 或 HPBar 的两种情况)
  300. const barNode = (this.hpBarRootNode && this.hpBarRootNode.isValid) ? this.hpBarRootNode : this.node;
  301. const barPath = this.getNodePath(barNode);
  302. const enemyNode = barNode.parent;
  303. if (!enemyNode) {
  304. console.warn(`[HPBarAnimation] ${barPath} 未找到父节点(敌人根节点),定位失败`);
  305. return;
  306. }
  307. // 先在同级父节点(敌人根)查找 EnemySprite,不存在则向上最多3级尝试
  308. let spriteNode: Node | null = enemyNode.getChildByName('EnemySprite');
  309. if (!spriteNode) {
  310. let ancestor = enemyNode.parent;
  311. let level = 1;
  312. while (!spriteNode && ancestor && level <= 3) {
  313. spriteNode = ancestor.getChildByName('EnemySprite');
  314. if (spriteNode) {
  315. console.warn(`[HPBarAnimation] ${barPath} 在更高层级找到 EnemySprite: ${this.getNodePath(spriteNode)} (levelUp=${level})`);
  316. break;
  317. }
  318. ancestor = ancestor.parent;
  319. level++;
  320. }
  321. }
  322. if (!spriteNode) {
  323. console.warn(`[HPBarAnimation] ${barPath} 未找到 EnemySprite(向上3级查找仍失败),敌人根: ${this.getNodePath(enemyNode)}`);
  324. return;
  325. }
  326. // 同时计算 UITransform 顶部与碰撞体顶部,最终取不低于图像顶部的值
  327. let colliderTopY: number | null = null;
  328. let uiTopY: number | null = null;
  329. let method = '';
  330. // 计算 UI 顶部
  331. const ui = spriteNode.getComponent(UITransform);
  332. if (ui) {
  333. const height = ui.contentSize.height * Math.abs(spriteNode.scale.y);
  334. uiTopY = spriteNode.position.y + (1 - ui.anchorPoint.y) * height;
  335. }
  336. // 计算碰撞体顶部(如有)
  337. const anyCollider = spriteNode.getComponent(Collider2D);
  338. if (anyCollider) {
  339. if (anyCollider instanceof BoxCollider2D) {
  340. const col = anyCollider as BoxCollider2D;
  341. colliderTopY = spriteNode.position.y + col.offset.y + col.size.height / 2;
  342. } else if (anyCollider instanceof CircleCollider2D) {
  343. const circle = anyCollider as CircleCollider2D;
  344. colliderTopY = spriteNode.position.y + circle.offset.y + circle.radius;
  345. }
  346. }
  347. let topY: number | null = null;
  348. if (this.useColliderForTop && colliderTopY !== null) {
  349. // 优先碰撞体,但不低于UI顶部
  350. topY = uiTopY !== null ? Math.max(colliderTopY, uiTopY) : colliderTopY;
  351. method = `ColliderPreferred(${anyCollider ? anyCollider.constructor.name : 'none'}) + clampToUI`;
  352. } else if (uiTopY !== null) {
  353. // 仅使用UITransform
  354. topY = uiTopY;
  355. method = `UITransform(height=${ui ? ui.contentSize.height : 'N/A'}, anchorY=${ui ? ui.anchorPoint.y : 'N/A'}, scaleY=${spriteNode.scale.y})`;
  356. } else if (colliderTopY !== null) {
  357. // 回退到碰撞体
  358. topY = colliderTopY;
  359. method = `ColliderOnly(${anyCollider ? anyCollider.constructor.name : 'none'})`;
  360. }
  361. if (topY === null) {
  362. console.warn(`[HPBarAnimation] ${barPath} EnemySprite 缺少 UITransform/Collider,无法计算顶部`);
  363. return;
  364. }
  365. // 将位置设置到血条节点自身(不要移动 Enemy 根节点)
  366. const current = barNode.position;
  367. const targetY = topY + this.offsetY;
  368. const moved = force || Math.abs(current.y - targetY) > 0.5;
  369. if (this.debugLogs) console.log(`[HPBarAnimation] 定位HPBar`, {
  370. barPath,
  371. enemyPath: this.getNodePath(enemyNode),
  372. spritePath: this.getNodePath(spriteNode),
  373. method,
  374. uiTopY,
  375. colliderTopY,
  376. topY,
  377. offsetY: this.offsetY,
  378. currentY: current.y,
  379. targetY,
  380. force,
  381. moved
  382. });
  383. if (moved) {
  384. barNode.setPosition(new Vec3(current.x, targetY, current.z));
  385. }
  386. }
  387. }