如何切换 CCSprite 的图像 [英] How to switch the image of a CCSprite

查看:17
本文介绍了如何切换 CCSprite 的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a CCSprite that is initialized using [CCSprite spriteWithSpriteFrameName:@"plist_file_key_here.png"]. I have already added all the sprites from my plist file to CCSpriteFrameCache. I have tried setting the texture like this:

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.

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

As I said in my comments, this doesn't work. I think it has something to do with the difference between using [CCSprite spriteWithFile:] and [CCSprite spriteWithSpriteFrameName:], which relies on sprite frames loaded into the CCSpriteFrameCache from a texture atlas. When using sprites loaded from a texture atlas, the texture of each sprite is equal to the texture of the sprite sheet. Is there any way around this or do I have to remove and recreate the sprite? If that is my only option, is there a way of removing a ccnode from its parent but preserving its children?

推荐答案

API参考救援!

当你有一个带有精灵框架的纹理时,你不想改变纹理而是精灵使用的精灵框架.你可以这样做:

When you have a texture with sprite frame, you don't want to change the texture but the sprite frame the sprite uses. That you can do as follows:

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

在 cocos2d v3 中它需要是:

in cocos2d v3 it would need to be:

sprite.spriteFrame = frame;

这篇关于如何切换 CCSprite 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆