6

我有一个使用[CCSprite spriteWithSpriteFrameName:@"plist_file_key_here.png"]. 我已经将 plist 文件中的所有精灵添加到 CCSpriteFrameCache。我试过这样设置纹理:

CCSpriteFrame * frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:name];
NSAssert(frame.texture!=nil, @"frame.texture can't equal nil"); //this works fine
[sprite setTexture:frame.texture]; //doesn't cause a white square to appear, just doesn't switch the image.

正如我在评论中所说,这不起作用。我认为这与 using[CCSprite spriteWithFile:]和之间的区别[CCSprite spriteWithSpriteFrameName:]有关,它依赖于从纹理图集加载到 CCSpriteFrameCache 中的精灵帧。当使用从纹理图集加载的精灵时,每个精灵的纹理等于精灵表的纹理。有什么办法可以解决这个问题,还是我必须删除并重新创建精灵?如果这是我唯一的选择,有没有办法从其父节点中删除 ccnode 但保留其子节点?

4

3 回答 3

17

救援的 API 参考!

当你有一个带有精灵帧的纹理时,你不想改变纹理,而是精灵使用的精灵帧。您可以执行以下操作:

CCSpriteFrameCache* cache = [CCSpriteFrameCache sharedSpriteFrameCache];
CCSpriteFrame* frame = [cache spriteFrameByName:name];
sprite.displayFrame = frame;

在 cocos2d v3 中它需要是:

sprite.spriteFrame = frame;
于 2011-11-19T00:02:13.423 回答
3

要将 CCSprite 的图像更改为动画,每帧之间有 1 秒:

CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];

CCSpriteFrame *frame1 = [cache spriteFrameByName:[NSString stringWithFormat:@"plist_file_key_here1.png"]];               
CCSpriteFrame *frame2 = [cache spriteFrameByName:[NSString stringWithFormat:@"plist_file_key_here2.png"]];             

NSArray *animFrames = [NSArray arrayWithObjects:frame1, frame2, nil];

CCAnimation *animation = [CCAnimation animationWithFrames:animFrames delay:1.0f];
[originalSprite runAction:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO]];
于 2011-11-19T03:27:35.777 回答
0

考虑一个名为 mySprite 的 CCSprite 对象。现在您可以按如下方式更改精灵的图像:

[mySprite setTexture:[[CCTextureCache sharedTextureCache] addImage:[Tools imageNameForName:"myNewImage.png"]]];

这会将 CCSprite 对象 mySprite 的图像更改为 myNewImage.png

注意:如果要更改的图像位于资产的任何特定文件夹中,那么您可以通过使用图像的整个路径来评估该图像。

于 2016-05-09T09:53:48.133 回答