123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import { _decorator, Component, Node, Sprite, SpriteFrame, resources } from 'cc';
- const { ccclass, property } = _decorator;
- @ccclass('AvatarManager')
- export class AvatarManager extends Component {
- @property({
- type: Sprite,
- tooltip: '头像显示的Sprite组件'
- })
- avatarSprite: Sprite = null;
- @property({
- tooltip: '头像资源的前缀,例如"avatar_"或者留空'
- })
- avatarPrefix: string = '';
- @property({
- tooltip: '头像资源的后缀,默认为".png"'
- })
- avatarSuffix: string = '.png';
- // 当前显示的头像ID
- private currentAvatarId: number = 0;
- /**
- * 根据角色ID加载并显示对应的头像
- * @param characterId 角色ID
- * @param callback 加载完成的回调函数
- */
- public loadAvatar(characterId: number, callback?: () => void): void {
- if (!this.avatarSprite) {
- console.error('头像Sprite组件未设置');
- callback && callback();
- return;
- }
- this.currentAvatarId = characterId;
-
- // 构建头像资源路径
- const avatarPath = `avatars/${this.avatarPrefix}${characterId}${this.avatarSuffix}/spriteFrame`;
-
- // 加载头像资源
- resources.load(avatarPath, SpriteFrame, (err, spriteFrame) => {
- if (err) {
- console.error(`加载头像失败: ${avatarPath}`, err);
- callback && callback();
- return;
- }
-
- // 设置头像
- this.avatarSprite.spriteFrame = spriteFrame;
-
- // 调用回调函数
- callback && callback();
- });
- }
- /**
- * 获取当前显示的头像ID
- */
- public getCurrentAvatarId(): number {
- return this.currentAvatarId;
- }
- /**
- * 清除当前显示的头像
- */
- public clearAvatar(): void {
- if (this.avatarSprite) {
- this.avatarSprite.spriteFrame = null;
- }
- this.currentAvatarId = 0;
- }
- /**
- * 加载并显示特定表情的头像
- * @param characterId 角色ID
- * @param emotion 表情名称(如"normal", "happy", "sad"等)
- * @param callback 加载完成的回调函数
- */
- public loadAvatarWithEmotion(characterId: number, emotion: string, callback?: () => void): void {
- if (!this.avatarSprite) {
- console.error('头像Sprite组件未设置');
- callback && callback();
- return;
- }
- this.currentAvatarId = characterId;
-
- // 构建头像资源路径,添加表情标识
- const avatarPath = `avatars/${this.avatarPrefix}${characterId}_${emotion}${this.avatarSuffix}`;
-
- // 加载头像资源
- resources.load(avatarPath, SpriteFrame, (err, spriteFrame) => {
- if (err) {
- console.error(`加载表情头像失败: ${avatarPath}`, err);
-
- // 尝试加载默认头像
- this.loadAvatar(characterId, callback);
- return;
- }
-
- // 设置头像
- this.avatarSprite.spriteFrame = spriteFrame;
-
- // 调用回调函数
- callback && callback();
- });
- }
- }
|