2011-05-04 58 views
0

我有2个按钮(左和右)和一个包含所有55个图像的精灵表。我想知道,使用按钮浏览每个精灵的最佳方式是什么?使用按钮更改精灵 - Cocos2d

E.G. 按下左键并添加第一个精灵。按下右键,第一个精灵将被删除,第二个精灵将被添加。等等,直到它到达最后的图像。

这是精灵表

#import "cocos2d.h" 


@interface GameScene : CCLayer { 

CCSpriteBatchNode *pspriteSheet 

} 

+(CCScene *) scene; 

@property (nonatomic, retain) CCSprite *p; 

@end 
---------------------------------------------------- 
#import "GameScene.h" 


@implementation GameScene 

@synthesize p = _p; 


+(CCScene *) scene 
{ 
    CCScene *scene = [CCScene node]; 
    GameScene *layer = [GameScene node]; 

    [scene addChild: layer]; 
    return scene; 
} 

-(id) init 
{ 
    if ((self = [super init])) 
    { 
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile: 
     @"PAnim.plist"]; 

     pspriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"PAnim.pvr.ccz"]; 

     [self addChild:pspriteSheet z:0]; 
} 
    return self; 
} 

- (void) dealloc 
{ 
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self); 

    _p = nil; 

    [CCSpriteFrameCache purgeSharedSpriteFrameCache]; 
    [CCTextureCache purgeSharedTextureCache]; 

    [super dealloc]; 
} 

我应该不断加入他们,消除他们?

E.G.

-(void)buttons:(CGPoint)touchLocation 
{ 
    if (CGRectContainsPoint(leftB.boundingBox, touchLocation) && tapP == YES && paused == NO) { 
     if (count == 1) 
     { 
      _p = [CCSprite spriteWithSpriteFrameName:@"p1.png"]; 
      [pspriteSheet addChild:_p]; 
      count = 2; 
      _p.position = ccp(240, 215); 
     } 
if (CGRectContainsPoint(rightB.boundingBox, touchLocation) && tapP == YES && paused == NO) { 
     if (count == 2) 
     { 
      [pspriteSheet removeChild:_p cleanup:YES]; 

      _p = [CCSprite spriteWithSpriteFrameName:@"p2.png"]; 
      _p.position = ccp(240, 215); 
      [pspriteSheet addChild:_p]; 

      count = 3; 
     } 
} 

这里就是 “按钮” 方法被调用

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 

    [self buttons:touchLocation]; 

    return TRUE; 
} 

回答

0

由于它使用spriteframe,您可以使用setDisplay框架:

CCSpriteFrame* frame = [[CCSpriteFrameCache sharedSpriteFrameCache]spriteFrameByName:@"spr1.png"]; 
[mySprite setDisplayFrame:frame]; 

这将节省内存,而不是总是添加和删除..

+0

我有多个精灵表使用相同的方法(我不知道这是否使differen CE)。我可以使用它,因为我得到“EXC_BAD_ACCESS”错误或精灵甚至没有出现。有任何想法吗? – Jonathan 2011-05-04 05:45:58

+0

我在“ccTouchBegan” – Jonathan 2011-05-04 05:49:43

+0

中调用了我的“ - (void)按钮:(CGPoint)touchlocation”,我不太确定,因为我只改变了同一个batchnode中的显示帧。 – xuanweng 2011-05-07 15:26:39