如何将CCSpriteFrame转换为CCTexture2D(Cocos2d)?

时间:2012-10-18 07:28:26

标签: iphone ios xcode cocos2d-iphone

  

可能重复:
  How to convert a CCSpriteFrame to a CCTexture2D (Cocos2d)

是否可以采用从CCSpriteFrameCache中获取的CCSpriteFrame,并将其转换为CCTexture2D?

我试过这个:

-(id)initWithFile:(NSString*)filename body:(b2Body*)body  original:(BOOL)original
{
    NSAssert(filename != nil, @"Invalid filename for sprite");

    CCTexture2D *texture =  [[[CCSpriteFrameCache sharedSpriteFrameCache]spriteFrameByName:filename ]texture];

    return [self initWithTexture:texture body:body original:original];
}     

但是在屏幕上显示整个spritesheet纹理而不仅仅是一帧。

此链接中存在类似问题:How to convert a CCSpriteFrame to a CCTexture2D (Cocos2d) 但我没有发现此链接的答案有用。

我也试过这个,但结果相同:

-(id)initWithFile:(CCSpriteFrame*)filename body:(b2Body*)body  original:(BOOL)original
{
   NSAssert(filename != nil, @"Invalid filename for sprite");

   CCSprite * sprite_ = [CCSprite spriteWithSpriteFrame:filename];
   CCTexture2D *texture =  [sprite_ texture];
   return [self initWithTexture:texture body:body original:original];

}

2 个答案:

答案 0 :(得分:0)

此代码适用于我(cocos2d 2.0)

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"walk_cpu_fighter_asleep.plist"];
CCSpriteFrame *fr = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"walk_cpu_fighter_asleep0001.png"];
CCSprite *spr = [CCSprite spriteWithSpriteFrame:fr];

CGPoint p = [[GEPlayGrid sharedPlayGrid] positionForTileAtX:1 andY:1];

spr.position = p;
[[GameEngine sharedGameEngine].mapProvider.mapUnitsLayer addChild:spr];

spriteWithSpriteFrame构造函数根据精灵框架中包含的裁剪规范正确裁剪。是绝对必需的纹理,你可以使用CCSprites吗?很难猜出你的代码中有什么 self 以及它扩展了什么:) ...但也许你可能想要initWithSpriteFrame:body:original。

答案 1 :(得分:0)

你有没有尝试过:

-(void) addSpriteFramesWithFile:(NSString*)plist textureFile:(NSString*)textureFileName

之后:

CCTexture2D *cachedTexture = [[CCTextureCache sharedTextureCache] textureForKey:textureFileName];