AvatarManager.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { _decorator, Component, Node, Sprite, SpriteFrame, resources } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('AvatarManager')
  4. export class AvatarManager extends Component {
  5. @property({
  6. type: Sprite,
  7. tooltip: '头像显示的Sprite组件'
  8. })
  9. avatarSprite: Sprite = null;
  10. @property({
  11. tooltip: '头像资源的前缀,例如"avatar_"或者留空'
  12. })
  13. avatarPrefix: string = '';
  14. @property({
  15. tooltip: '头像资源的后缀,默认为".png"'
  16. })
  17. avatarSuffix: string = '.png';
  18. // 当前显示的头像ID
  19. private currentAvatarId: number = 0;
  20. /**
  21. * 根据角色ID加载并显示对应的头像
  22. * @param characterId 角色ID
  23. * @param callback 加载完成的回调函数
  24. */
  25. public loadAvatar(characterId: number, callback?: () => void): void {
  26. if (!this.avatarSprite) {
  27. console.error('头像Sprite组件未设置');
  28. callback && callback();
  29. return;
  30. }
  31. this.currentAvatarId = characterId;
  32. // 构建头像资源路径
  33. const avatarPath = `avatars/${this.avatarPrefix}${characterId}${this.avatarSuffix}/spriteFrame`;
  34. // 加载头像资源
  35. resources.load(avatarPath, SpriteFrame, (err, spriteFrame) => {
  36. if (err) {
  37. console.error(`加载头像失败: ${avatarPath}`, err);
  38. callback && callback();
  39. return;
  40. }
  41. // 设置头像
  42. this.avatarSprite.spriteFrame = spriteFrame;
  43. // 调用回调函数
  44. callback && callback();
  45. });
  46. }
  47. /**
  48. * 获取当前显示的头像ID
  49. */
  50. public getCurrentAvatarId(): number {
  51. return this.currentAvatarId;
  52. }
  53. /**
  54. * 清除当前显示的头像
  55. */
  56. public clearAvatar(): void {
  57. if (this.avatarSprite) {
  58. this.avatarSprite.spriteFrame = null;
  59. }
  60. this.currentAvatarId = 0;
  61. }
  62. /**
  63. * 加载并显示特定表情的头像
  64. * @param characterId 角色ID
  65. * @param emotion 表情名称(如"normal", "happy", "sad"等)
  66. * @param callback 加载完成的回调函数
  67. */
  68. public loadAvatarWithEmotion(characterId: number, emotion: string, callback?: () => void): void {
  69. if (!this.avatarSprite) {
  70. console.error('头像Sprite组件未设置');
  71. callback && callback();
  72. return;
  73. }
  74. this.currentAvatarId = characterId;
  75. // 构建头像资源路径,添加表情标识
  76. const avatarPath = `avatars/${this.avatarPrefix}${characterId}_${emotion}${this.avatarSuffix}`;
  77. // 加载头像资源
  78. resources.load(avatarPath, SpriteFrame, (err, spriteFrame) => {
  79. if (err) {
  80. console.error(`加载表情头像失败: ${avatarPath}`, err);
  81. // 尝试加载默认头像
  82. this.loadAvatar(characterId, callback);
  83. return;
  84. }
  85. // 设置头像
  86. this.avatarSprite.spriteFrame = spriteFrame;
  87. // 调用回调函数
  88. callback && callback();
  89. });
  90. }
  91. }