【问题标题】:""CCSprite is not using the same texture id"" workaround?“”CCSprite 没有使用相同的纹理ID“”解决方法?
【发布时间】:2013-07-17 04:00:28
【问题描述】:
我通过 SpriteSheets 使用 CCSpriteBatchNode 和 CCSpriteFrameCache 为整个身体设置动画。现在,用户可以将他自己的图片添加到该正文中,当我尝试 addChild 到 Spritesheet 时会崩溃并出现错误 “CCSprite 未使用相同的纹理 ID "
现在我知道面部 CCSprite 不在那个缓存/纹理中(它是通过 texturepacker 创建的)并且崩溃是正常的,但我想知道是否有一种解决方法,因为我必须通过用户交互为该身体添加一张脸并为该身体设置动画。到目前为止,使用 spritesheets 是动画的最佳选择。有人吗??
【问题讨论】:
标签:
ios
cocos2d-iphone
sprite-sheet
texturepacker
【解决方案1】:
在这种情况下,您可以做的是给用户拍照,然后根据用户的图像制作纹理。
然后将该纹理添加到 CCTextureCache 。现在你有了用户图像的纹理。现在您可以在动画中使用该纹理了。
从 Sprite 制作纹理(您可以从用户图像制作 sprite)
CCSprite *spr = nil;//your sprite
CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:spr.contentSize.width height:spr.contentSize.height];
spr.anchorPoint = ccp(0, 0);
spr.position = ccp(0, 0);
[renderTexture addChild:spr];
[renderTexture begin];
[spr draw]; // or [spr visit];
[renderTexture end];
CCTexture2D *result = renderTexture.sprite.texture;
将该纹理添加到纹理缓存中。
[[CCTextureCache sharedTextureCache] addTexture]
【解决方案2】:
当您创建 CCSpriteBatchNode 时,它会链接到单个 texture。这就是CCSpriteBatchNode 的重点:绘制使用相同纹理的不同精灵以减少 OpenGL 绘制调用并提高效率。
最简单的解决方法(如果您尚未达到性能关键点)是使用常规的CCLayer 而不是CCSpriteBatchNode。
如果您仍想将不同的CCSprites(例如,角色的身体、四肢和头部)添加到同一个CCSpriteBatchNode,您需要构建一个单独的精灵表(或纹理包)包含您需要添加到CCSpriteBatchNode 的所有身体部位。这个单一的精灵表将是CCSpriteBatchNode 将使用的唯一一个。您将无法添加未使用此精灵表的CCSprites。
【解决方案3】:
您不能手动将CCSprite 添加到SpriteSheets。因为当您使用 texturepacker 创建动画 Sprite 时,我希望您知道它也是使用 .plist 文件创建的,并且它会从它的大小中获取图像。
当您手动添加 CCSprite 时,在 SpriteFramesWithFile 中也找不到它。可能是你出错了。
另一种不使用 texturepacker
添加动画 CCSprite 的方法
CCSprite *dog = [CCSprite spriteWithFile:@"dog1.gif"];
dog.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:dog z:2];
NSMutableArray *animFrames = [NSMutableArray array];
for( int i=1;i<=5;i++)
{
NSString* file = [NSString stringWithFormat:@"dog%d.gif", i];
CCTexture2D* texture = [[CCTextureCache sharedTextureCache] addImage:file];
CGSize texSize = texture.contentSize;
CGRect texRect = CGRectMake(0, 0, texSize.width, texSize.height);
CCSpriteFrame* frame = [CCSpriteFrame frameWithTexture:texture rect:texRect];
[animFrames addObject:frame];
}
CCAnimation * animation = [CCAnimation animationWithSpriteFrames:animFrames];
animation.delayPerUnit = 0.07f;
animation.restoreOriginalFrame = YES;
CCAnimate *animAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:animation]];
[dog runAction:animAction];
上面的代码只是描述了如何在不使用texturepacker的情况下添加动画CCSprite
您还可以在这里更改图像数组,以便您也可以手动添加图像。