HPBarAnimation.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. this.updateBarPosition();
  119. if (this.hpBarRootNode && this.hpBarRootNode.isValid) {
  120. this.hpBarRootNode.active = true;
  121. if (this.debugLogs) console.log(`[HPBarAnimation] showHealthBar: active=true path=${this.getNodePath(this.hpBarRootNode)}`);
  122. } else {
  123. if (this.debugLogs) console.warn(`[HPBarAnimation] showHealthBar: hpBarRootNode 无效,使用当前节点 path=${this.getNodePath(this.node)}`);
  124. this.node.active = true;
  125. }
  126. // 清除隐藏定时器
  127. if (this.hideTimer) {
  128. clearTimeout(this.hideTimer);
  129. this.hideTimer = null;
  130. }
  131. }
  132. /**
  133. * 隐藏血条
  134. */
  135. public hideHealthBar() {
  136. if (this.hpBarRootNode && this.hpBarRootNode.isValid) {
  137. this.hpBarRootNode.active = false;
  138. if (this.debugLogs) console.log(`[HPBarAnimation] hideHealthBar: active=false path=${this.getNodePath(this.hpBarRootNode)}`);
  139. } else {
  140. if (this.debugLogs) console.warn(`[HPBarAnimation] hideHealthBar: hpBarRootNode 无效,使用当前节点 path=${this.getNodePath(this.node)}`);
  141. this.node.active = false;
  142. }
  143. }
  144. /**
  145. * 延迟隐藏血条
  146. * @param delay 延迟时间(秒)
  147. */
  148. private scheduleHideHealthBar(delay: number = 3.0) {
  149. if (this.debugLogs) console.log(`[HPBarAnimation] scheduleHideHealthBar: delay=${delay}s path=${this.getNodePath(this.hpBarRootNode || this.node)}`);
  150. // 清除之前的定时器
  151. if (this.hideTimer) {
  152. clearTimeout(this.hideTimer);
  153. }
  154. // 设置新的定时器
  155. this.hideTimer = setTimeout(() => {
  156. this.hideHealthBar();
  157. this.hideTimer = null;
  158. }, delay * 1000);
  159. }
  160. /**
  161. * 更新血条进度并播放动画
  162. * @param newProgress 新的血量百分比 (0-1)
  163. * @param showBar 是否显示血条(默认为true)
  164. */
  165. public updateProgress(newProgress: number, showBar: boolean = true) {
  166. const enemyName = this.node ? this.node.name : 'Unknown';
  167. if (this.debugLogs) console.log(`[HPBarAnimation] updateProgress(showBar=${showBar}) ${this.currentProgress} -> ${newProgress}`);
  168. if (!this.redProgressBar || !this.yellowProgressBar) {
  169. console.warn(`[HPBarAnimation] [${enemyName}] 红色或黄色血条组件未初始化`);
  170. return;
  171. }
  172. newProgress = Math.max(0, Math.min(1, newProgress));
  173. if (showBar) {
  174. this.showHealthBar();
  175. this.updateBarPosition();
  176. }
  177. // 如果血量增加或没有变化,直接更新
  178. if (newProgress >= this.currentProgress) {
  179. this.currentProgress = newProgress;
  180. this.targetProgress = newProgress;
  181. // 同步更新两个血条
  182. if (this.redProgressBar && this.redProgressBar.isValid) {
  183. this.redProgressBar.progress = newProgress;
  184. }
  185. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  186. this.yellowProgressBar.progress = newProgress;
  187. }
  188. this.updateBarDisplay();
  189. // 如果血量满了,立即隐藏血条
  190. if (newProgress >= 1.0) {
  191. this.scheduleHideHealthBar(1.0); // 1秒后隐藏
  192. } else if (showBar) {
  193. this.scheduleHideHealthBar(3.0); // 3秒后隐藏
  194. }
  195. return;
  196. }
  197. // 血量减少时播放黄色血皮滑动动画
  198. this.playDamageAnimation(newProgress);
  199. }
  200. /**
  201. * 播放伤害动画
  202. * @param newProgress 新的血量百分比
  203. */
  204. private playDamageAnimation(newProgress: number) {
  205. console.log(`[HPBarAnimation] 开始播放伤害动画:${this.currentProgress} -> ${newProgress}`);
  206. // 停止当前正在运行的动画,避免动画冲突
  207. if (this.currentTween) {
  208. this.currentTween.stop();
  209. this.currentTween = null;
  210. }
  211. this.targetProgress = newProgress;
  212. // 保存原始血量作为黄色血条起始位置
  213. const originalProgress = this.currentProgress;
  214. // 1. 立即更新红色血条到新的血量值
  215. this.currentProgress = newProgress;
  216. if (this.redProgressBar && this.redProgressBar.isValid) {
  217. this.redProgressBar.progress = newProgress;
  218. }
  219. // 2. 黄色血条从原血量滑动到新血量位置
  220. // 黄色血条保持在原始位置
  221. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  222. this.yellowProgressBar.progress = originalProgress;
  223. }
  224. this.updateBarDisplay();
  225. // 创建滑动动画,先暂停0.4秒再滑动
  226. this.currentTween = tween({ progress: originalProgress })
  227. .delay(0.4) // 暂停0.4秒
  228. .to(0.3, { progress: newProgress }, {
  229. onUpdate: (target) => {
  230. // 动画过程中更新黄色血条进度
  231. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  232. this.yellowProgressBar.progress = target.progress;
  233. this.updateBarDisplay();
  234. }
  235. },
  236. onComplete: () => {
  237. // 动画完成后黄色血条进度等于当前血量
  238. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  239. this.yellowProgressBar.progress = newProgress;
  240. this.updateBarDisplay();
  241. }
  242. // 清除动画引用
  243. this.currentTween = null;
  244. // 动画完成后延迟隐藏血条
  245. if (newProgress > 0) {
  246. this.scheduleHideHealthBar(3.0); // 3秒后隐藏血条
  247. }
  248. }
  249. })
  250. .start();
  251. }
  252. /**
  253. * 获取当前血量百分比
  254. */
  255. public getCurrentProgress(): number {
  256. return this.currentProgress;
  257. }
  258. /**
  259. * 重置血条到满血状态
  260. */
  261. public resetToFull() {
  262. this.updateProgress(1.0, false); // 重置时不显示血条
  263. }
  264. /**
  265. * 重置血条到满血状态并隐藏
  266. */
  267. public resetToFullAndHide() {
  268. this.currentProgress = 1.0;
  269. this.targetProgress = 1.0;
  270. // 同步更新两个血条到满血状态
  271. if (this.redProgressBar && this.redProgressBar.isValid) {
  272. this.redProgressBar.progress = 1.0;
  273. }
  274. if (this.yellowProgressBar && this.yellowProgressBar.isValid) {
  275. this.yellowProgressBar.progress = 1.0;
  276. }
  277. this.updateBarDisplay();
  278. // 立即隐藏血条
  279. this.hideHealthBar();
  280. }
  281. onDestroy() {
  282. // 清理正在运行的动画,防止内存泄漏
  283. if (this.currentTween) {
  284. this.currentTween.stop();
  285. this.currentTween = null;
  286. }
  287. // 清理隐藏血条的定时器,防止内存泄漏
  288. if (this.hideTimer) {
  289. clearTimeout(this.hideTimer);
  290. this.hideTimer = null;
  291. }
  292. }
  293. public updateBarPosition(force: boolean = false) {
  294. // 以血条节点作为基准(兼容脚本挂在 Enemy 或 HPBar 的两种情况)
  295. const barNode = (this.hpBarRootNode && this.hpBarRootNode.isValid) ? this.hpBarRootNode : this.node;
  296. const barPath = this.getNodePath(barNode);
  297. const enemyNode = barNode.parent;
  298. if (!enemyNode) {
  299. console.warn(`[HPBarAnimation] ${barPath} 未找到父节点(敌人根节点),定位失败`);
  300. return;
  301. }
  302. // 先在同级父节点(敌人根)查找 EnemySprite,不存在则向上最多3级尝试
  303. let spriteNode: Node | null = enemyNode.getChildByName('EnemySprite');
  304. if (!spriteNode) {
  305. let ancestor = enemyNode.parent;
  306. let level = 1;
  307. while (!spriteNode && ancestor && level <= 3) {
  308. spriteNode = ancestor.getChildByName('EnemySprite');
  309. if (spriteNode) {
  310. console.warn(`[HPBarAnimation] ${barPath} 在更高层级找到 EnemySprite: ${this.getNodePath(spriteNode)} (levelUp=${level})`);
  311. break;
  312. }
  313. ancestor = ancestor.parent;
  314. level++;
  315. }
  316. }
  317. if (!spriteNode) {
  318. console.warn(`[HPBarAnimation] ${barPath} 未找到 EnemySprite(向上3级查找仍失败),敌人根: ${this.getNodePath(enemyNode)}`);
  319. return;
  320. }
  321. // 同时计算 UITransform 顶部与碰撞体顶部,最终取不低于图像顶部的值
  322. let colliderTopY: number | null = null;
  323. let uiTopY: number | null = null;
  324. let method = '';
  325. // 计算 UI 顶部
  326. const ui = spriteNode.getComponent(UITransform);
  327. if (ui) {
  328. const height = ui.contentSize.height * Math.abs(spriteNode.scale.y);
  329. uiTopY = spriteNode.position.y + (1 - ui.anchorPoint.y) * height;
  330. }
  331. // 计算碰撞体顶部(如有)
  332. const anyCollider = spriteNode.getComponent(Collider2D);
  333. if (anyCollider) {
  334. if (anyCollider instanceof BoxCollider2D) {
  335. const col = anyCollider as BoxCollider2D;
  336. colliderTopY = spriteNode.position.y + col.offset.y + col.size.height / 2;
  337. } else if (anyCollider instanceof CircleCollider2D) {
  338. const circle = anyCollider as CircleCollider2D;
  339. colliderTopY = spriteNode.position.y + circle.offset.y + circle.radius;
  340. }
  341. }
  342. let topY: number | null = null;
  343. if (this.useColliderForTop && colliderTopY !== null) {
  344. // 优先碰撞体,但不低于UI顶部
  345. topY = uiTopY !== null ? Math.max(colliderTopY, uiTopY) : colliderTopY;
  346. method = `ColliderPreferred(${anyCollider ? anyCollider.constructor.name : 'none'}) + clampToUI`;
  347. } else if (uiTopY !== null) {
  348. // 仅使用UITransform
  349. topY = uiTopY;
  350. method = `UITransform(height=${ui ? ui.contentSize.height : 'N/A'}, anchorY=${ui ? ui.anchorPoint.y : 'N/A'}, scaleY=${spriteNode.scale.y})`;
  351. } else if (colliderTopY !== null) {
  352. // 回退到碰撞体
  353. topY = colliderTopY;
  354. method = `ColliderOnly(${anyCollider ? anyCollider.constructor.name : 'none'})`;
  355. }
  356. if (topY === null) {
  357. console.warn(`[HPBarAnimation] ${barPath} EnemySprite 缺少 UITransform/Collider,无法计算顶部`);
  358. return;
  359. }
  360. // 将位置设置到血条节点自身(不要移动 Enemy 根节点)
  361. const current = barNode.position;
  362. const targetY = topY + this.offsetY;
  363. const moved = force || Math.abs(current.y - targetY) > 0.5;
  364. if (this.debugLogs) console.log(`[HPBarAnimation] 定位HPBar`, {
  365. barPath,
  366. enemyPath: this.getNodePath(enemyNode),
  367. spritePath: this.getNodePath(spriteNode),
  368. method,
  369. uiTopY,
  370. colliderTopY,
  371. topY,
  372. offsetY: this.offsetY,
  373. currentY: current.y,
  374. targetY,
  375. force,
  376. moved
  377. });
  378. if (moved) {
  379. barNode.setPosition(new Vec3(current.x, targetY, current.z));
  380. }
  381. }
  382. }